Saturday, 8 June 2013

Java code to reverse the digits of Integer

Code
---------
import java.util.Scanner;

class ReverseDigits {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int i = reverseDigits(s.nextInt());
System.out.println(i);
}

public static int reverseDigits(int k) {
String st = k + "";
StringBuffer sb = new StringBuffer(st).reverse();
return new Integer(sb.toString()).intValue();
}
}

Sample output
-------------------
Please enter a number
1234
4321


Explanation
---------------------
 reverseDigits(): This is a method that takes an integer and then convert to string and then reverse it and then return an int.
 st=k+""; This is an easy way of converting an int to string. Appending "".
 Nothing in fact is appended, an open and close of the double quotes just does the thing.

 sb=new StringBuffer(st).reverse(); This statement creates a StringBuffer object of the string (which is the given int) and then the reverse method reverses the string.

 new Integer(sb.toString()).intValue(): Gives the int value of string. The java.lang.Integer class contains this. The constructor here takes a java.lang.String as parameter.

No comments:

Post a Comment