Dart: Reverse an integer number
In this challenge, we are going to reverse an integer number. For example, if you got the digits 321, reversing them would give you 123
This solution will use a while loop, modulo, and integer division.
First, we need to obtain the last digit of the given number, which is always the remainder when dividing it by 10. For example, to get the 1 from the number 321:
Now that we know how to get the last digit of the given number, we need to store that digit in a variable and remove it from the given number.
int number = 321;
int lastDigit = number % 10;
// TODO: remove the digit from the given number
number = ???????????;
Removing the last digit from the given number is straightforward. We divide by 10, and the quotient will not contain the last digit:
So our code would look like this:
int number = 321;
int lastDigit = number % 10;
number ~/= 10;
Now, we need to repeat this code as long as the number is not equal to 0, so we'll add a loop:
int number = 321;
// loop while the number is not 0
while (number != 0) {
int lastDigit = number % 10;
number ~/= 10;
}
Finally, we must create a variable int reversed
to add the last digit. Since we need to add the digit to the right
side of the previous digit each iteration, and we can't use concatenation, we'll multiply the reversed number
by 10 to add the digit. The final code will look like this:
I have noticed that some people say this code does not work if the first digit of the given number is 0. For example, the number 0123 should be reversed to 3210. Well, the answer is that when storing 0123 in an integer variable, it automatically becomes 123, as the leading zero has no value. Therefore, when reversed, it becomes 321.