Method to reverse String using While Loop
Hello, I am trying to create a program that will output the reverse of any string of integers. I got the program to work with some help from another forum, but I'm just not understanding why it works.
Specifically, what purpose is the + 10 * result serving? :confused:
I can tell that it is allowing result to store all the modulus results instead of just replacing them as the loops continues, but I want to understand why.
I've tested the program without the +10*result, and it doesn't work because the return result will only store the last result. For example, if you enter 654, instead of getting 456, you would only get 4 since result keeps getting replaced by 6, 5 & 4.
Here is the code: I appreciate any feedback or help! ;)
public static void main(String[] args) {
String num1Str;
int num1, num2;
num1Str = JOptionPane.showInputDialog("Enter a positive integer");
num1 = Integer.parseInt(num1Str);
//call method
num2 = reverse(num1);
JOptionPane.showMessageDialog(null, "The reversed integer for " + num1 + " is " + num2);
}
public static int reverse(int myInput){
int result = 0 ;
while ( myInput > 0 )
{
result = myInput % 10 + 10 * result;
myInput /= 10 ;
}
return result ;
}
Re: Method to reverse String using While Loop
Quote:
what purpose is the 10 * result
Look at the value of result and the value of result*10. The second one has all the digits shifted left 1 decimal digit and a 0 added on the right.
Think about how you would build a number given a bunch of digits and a power of 10 for each.
2*1000 + 3 * 100 + 4 * 10 + 5
What if I give you the numbers one by one: 2 and then 3 and then 4 and then 5. what is the result
Now what if there are only 2 numbers: 2 and 3 and I give them to you one at a time.
Now suppose there are 8 numbers one at a time.
etc
Each new number is the old*10 plus the new number.
Re: Method to reverse String using While Loop