Integer logic 1234 = 4 *10^3+3*10^2+2*10^1+1*10^0
String logic Sarav= replace the indices value till you reach the middle.
package com.sarav.util;
/**
* @author sparamasivan
*
*/
public class ReverseUtil {
public static void main(String[] args) {
System.out.println(reverse(1234));
System.out.println(reverse("Sarav"));
}
public static int reverse(int number){
int length=String.valueOf(number).length();
int reverse=0;
while(length>0){
//int tens=(int)(Math.pow(10.00,length-1));
//reverse=reverse + ((number%10)*tens);
reverse=(reverse*10) + ((number%10));
number= number/10;
length--;
}
return reverse;
}
public static String reverse( String s ) {
int length = s.length(), last = length - 1;
char[] chars = s.toCharArray();
for ( int i = 0; i < length/2; i++ ) {
char c = chars[i];
chars[i] = chars[last - i];
chars[last - i] = c;
}
return new String(chars);
}
}
1 comment:
Hi..instead of using Math.Pow.. we can use the below statement to form the reversed number...
r_num=0;
r_num=r_num*10+remainder;
Post a Comment