1. Member
Join Date
Feb 2010
Posts
75
Rep Power
0

## reversing digits

Alright I've got this problem mostly figured out. I'm supposed to take a string of digits and then reverse it. It works except for one thing. If the user inputs 31000, then it should output 13. Likewise, if the user inputs 00013, it should display 31000. However, I come out with 00013 and 31, respectively. how can I remove the leading zeros and keep it from automatically truncating that 00013 to 13?

2. Member
Join Date
Feb 2010
Posts
75
Rep Power
0
Forgot to post my code, here it is.
Java Code:
```import java.util.Scanner;
import java.lang.Math;
import java.lang.String;

public class DigitReverse {

public static long reverseDigit(long num) {

long rnum;

rnum = num % 10;

return(rnum);
}
public static void main(String[] args) {
long num;
final int FLAG = 0;
int restart;
String snum;
int length;
long rdigit;
Scanner input = new Scanner(System.in);

do{System.out.print("Enter the number: ");
num = input.nextLong();
snum = Long.toString(num);
length = snum.length();
if (num >= 0) {
System.out.print("The reverse of your number is: ");
for (int i = 1; i <= length; i++) {
rdigit = reverseDigit(num);
System.out.print(rdigit);
num /= 10;
}
} else {
num = Math.abs(num);
System.out.print("The reverse of your number is: -");
for (int i = 1; i < length; i++) {
rdigit = reverseDigit(num);
System.out.print(rdigit);
num /= 10;
}
}
System.out.println();
System.out.print("Enter 0 to quit, any other number to continue: ");
restart = input.nextInt();
}while(restart != FLAG);

}
}```

3. Originally Posted by gandalf5166
Alright I've got this problem mostly figured out. I'm supposed to take a string of digits and then reverse it. It works except for one thing. If the user inputs 31000, then it should output 13. Likewise, if the user inputs 00013, it should display 31000. However, I come out with 00013 and 31, respectively. how can I remove the leading zeros and keep it from automatically truncating that 00013 to 13?
Numbers don't have leading zeros; maybe you want to pass them as their String representation instead? (i.e. the input 00013 doesn't exist and can't be passed to your method).

kind regards,

Jos

4. Member
Join Date
Feb 2010
Posts
75
Rep Power
0
That's a good idea, and I could convert the string back to a number after it switched the digits that way it would get rid of the leading zeros from after it reverses 31000.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•