In my last blog post, I had fun going over some simple algorithms including string reversal, palindromes, and my favorite, anagrams. I thought I’d continue with a couple of slightly more difficult problems this week in integer reversal and one of my all-time favorite problems, the classic FizzBuzz. If you’d like to check out my last blog post, you can find it here.
Integer Reversal
While this one might sound simple, there are a couple of caveats to consider. First, if we are given a negative integer, we are to reverse the integer while keeping the integer negative. In short, a negative integer stays negative. Second, if the number ends in zeros, the numbers should be returned without the zeros at the beginning. For example, if we are to reverse the number 100, we would NOT want to return 001. Instead, we would want to return 1. If you read my last post that included reversing strings, you might have a pretty good idea of what we need to do.
When we reversed a string, we used the split()
method to convert the string into an array before calling the reverse()
array method. We could use a similar approach to this problem but since split()
is a string method, it simply would not work on our integer. That is where the toString()
method comes in handy.
“The
toString()
method returns a string representing the specified number object.”
Using the toString()
method, we can call it on our number before using the split()
method. Let's go over the steps before we start coding.
Solution
- Call
toString()
on integer to convert it into a string. - Split integer into array.
- Reverse array using the
reverse()
function. - Join array.
- Convert back into integer.
Let’s write our first line of code. Remember, we need to convert the integer to a string. Let's assign the variable num
to the argument n
being converted to a string, split into an array, reversed, and then joined using the join()
method.
function reverseInt(n) {const num = n.toString().split('').reverse().join('')
//converts 2853 into "3582"}
So far, we’ve reversed the string and we just need to convert the string back into an integer before returning it. Let’s do that now.
function reverseInt(n) {const num = n.toString().split('').reverse().join('')
//converts 2853 into "3582"return parseInt(num)
//takes string and parses it into an integer. "3582" becomes 3582}
That seems to be the solution but as it stands now, passing a negative number to this function does not return the desired integer.
reverseInt(-321)$ 123
While this can be solved in a number of ways, I’m going to go over a simple and easy to understand solution using conditional statements. Feel free to refactor the code but since this is a simple tutorial, I’ll keep my solution to be easy to comprehend.
function reverseInt(n) {const num1 = n.toString().split('').reverse().join('')if (n < 0)
/// if n is negative{return parseInt(num1) * -1}
//since - sign is lost during conversion, we can multiply by -1 to turn it back into a negative integer after flipping.else {return parseInt(num1)}
//nothing to do if positive}
Let’s talk about how I solved it. Before the conditional was added, our negative sign was lost during the conversion. That's no problem. If the argument we received is less than 0, we know it was a negative number. If we know it's a negative number, we can simply multiply it by -1 to return a negative number that is flipped.
If not, we do nothing and returned the reversed integer.
Now that you understand how it works, we can refactor a tiny bit by using a ternary operator.
function reverseInt(n) {const num1 = n.toString().split('').reverse().join('')return (n < 0 ? parseInt(num1) * -1 : parseInt(num1))}
FizzBuzz
If you are unfamiliar with this classic problem, let’s go over the requirements.
We will be writing a small program that console logs the numbers from 1 to n. For multiples of three, print “fizz” instead of the number, and for the multiples of five, print “buzz”. For numbers that are multiples of both three and five, print “fizzbuzz”.
Let’s take a look at an example.
fizzBuzz(15)// expected output
//:1
//:2
//:fizz
//:4
//:buzz
//:fizz
//:7
//:8
//:fizz
//:buzz
//:11
//:fizz
//:13
//:14
//:fizzbuzz
While this problem may look intimidating at first, the requirements are pretty straightforward. The solution is also straightforward if you’ve ever encountered the remainder operator in Javascript.
The remainder operator (
%
) returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
Here is the official documentation for the remainder operator.
We’ll also need to iterate with a simple for
loop.
Official Docs on for loops.
Solution
- Create
for
loop. - Iterate through each number — 1 through
n
- Use a conditional statement to determine if “fizz”, “buzz”, or “fizzbuzz” should be printed.
function fizzBuzz(n) {
for (let i = 1; i <= n;i++) {
/// for loop will iterate through each number from 1 to n
}
}
For our purposes, we will start the iteration at 1. Now that we have a loop going, we need to set a few conditional statements to determine what we need to print. We’ll go through each one starting with “fizzbuzz”. Before we code, I’ll give you a brief refresher on how the remainder operator works.
Remember, the remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
console.log(12 % 5);
// expected output: 2
console.log(10 % 3)
// expected output: 1
console.log(4 % 2)
// expected output: 0
console.log(9 % 5)
// expected output: 4
So if a number is a multiple of 5, there will be a remainder of 0 when using the remainder operator. If a number is a multiple of 3 the same rule applies.
console.log(30 % 5)
// expected output: 0
console.log(10 % 5)
// expected output: 0
console.log(55 % 5)
// expected output: 0
Now, let's write our first conditional statement for “fizzbuzz”. Remember, multiples of 3 AND 5 should print “fizzbuzz”.
function fizzBuzz(n) {
for (let i = 1; i <= n;i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log('fizzbuzz')
}
///if i is a multiple of 3 AND 5, print "fizzbuzz" }
}
Now, we’ll move on to multiples of 3 which should print “fizz”
function fizzBuzz(n) {
for (let i = 1; i <= n;i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log('fizzbuzz')
}
else if (i % 3 === 0) {
console.log('fizz')
}
/// else if the remainder of dividing by 3 is 0, print
/// "fizz" }
}
Next, we need to print “buzz” for multiples of 5.
function fizzBuzz(n) {
for (let i = 1; i <= n;i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log('fizzbuzz')
}
else if (i % 3 === 0) {
console.log('fizz')
}
else if (i % 5 === 0) {
console.log('buzz')
} /// else if the remainder of dividing by 5 is 0
/// print "buzz"
}
}
Finally, if the number is not a multiple of 15, 5, or 3, print the number as it is.
function fizzBuzz(n) {
for (let i = 1; i <= n;i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log('fizzbuzz')
}
else if (i % 3 === 0) {
console.log('fizz')
}
else if (i % 5 === 0) {
console.log('buzz')
}
else {
console.log(i)
}
}
}
And that’s it! If you’re good with numbers, you might have figured out that numbers that are both multiples of 3 and 5 are the same as multiples of 15. With that in mind, you’d be correct if you replaced (i % 3 === 0 && i % 5 === 0)
with (i % 15 === 0)
.
Conclusion
Like most algorithms, there are many solutions! Open up a Javascript playground and give these a shot. I’m sure you’ll come across many ways to refactor these solutions! Good luck and thanks for reading!