Smith
Smith

Reputation: 31

Make 2 digit number to a 3 digit number and reverse it

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

Answers (4)

Tejas Jadhav
Tejas Jadhav

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

Andreas
Andreas

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

Elliott Frisch
Elliott Frisch

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

Josh Chappelle
Josh Chappelle

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

Related Questions