Reputation: 31
99
to 099
and reverse it = 990
This is my code but it's not changing the number
. Why?
int number = 99;
String strI = String.format("%03d", number);
new StringBuilder(strI).reverse().toString();
number = Integer.parseInt(strI);
return number;
Upvotes: 1
Views: 7626
Reputation: 93
You have to assign the output of StringBuilder
to a variable and use that variable for Integer parsing.
Example
public class Reverse {
public static void main(String args[]) {
String s = String.format("%03d", 99);
String o = new StringBuilder(s).reverse().toString();
int number = Integer.parseInt(o);
System.out.println(number);
}
}
Upvotes: 2
Reputation: 159127
Alternate non-string version (faster):
int number = 99, result = 0;
for (int i = 0; i < 3; i++, number /= 10)
result = result * 10 + number % 10;
return result;
Upvotes: 2
Reputation: 201477
You aren't assigning the result of toString
back to strI
.
I think you wanted
strI = new StringBuilder(strI).reverse().toString();
Upvotes: 6
Reputation: 1588
String strI = String.format("%03d", number);
strI = new StringBuilder(strI).reverse().toString(); //Capture the result into strI
number = Integer.parseInt(strI);
return number;
Upvotes: 2