Method 1 - Without using any other data structure. Making extensive use of % operator. I love this method and you will love it too.
static int rev(int number) {
int rev = 0;
while (true) {
int digit = number % 10;
number = (number - digit) / 10;
rev += digit;
if (number < 10) {
rev *= 10;
rev += number;
break;
} else {
rev *= 10;
}
}
return rev;
}
Method 2 - Using StringBuffer and String
static int rev2(int number){
int rev2 = 0;
String numString = Integer.toString(number);
String rev2String = "";
StringBuffer stringBuffer = new StringBuffer();
for(int i = numString.length() - 1 ; i >=0; i--){
stringBuffer.append(numString.charAt(i));
}
rev2String = stringBuffer.toString();
rev2 = Integer.parseInt(rev2String);
return rev2;
}
No comments:
Post a Comment