Problem Statement
Write a Java program to reverse a given number
Condition
Input will only be a positive interger and will not have any characters
Input
12345
Output
54321
Explanation
Solution1-Explanation Number modulo 10 will give the last digit as result. (ie., 12345 % 10 = 5). Again dividing the same number by 10 will give the remaining digits except last one. Solution2-Explanation StringBuffer's append method concats the given input to the buffer. StringBuffer's reverse method reverses the contents of the StringBuffer.
code:
import java.util.Scanner;
public class Solution1{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int digit = sc.nextInt();
sc.close();
System.out.print("Reverse of the number is ");
if(digit == 0)
System.out.print(0);
else {
while(digit!=0){
System.out.print(digit%10);
digit /= 10;
}
}
}
}
or
public static void main(String[] args) { |
Scanner input = new Scanner(System.in); |
int number = input.nextInt(); |
StringBuffer str=new StringBuffer(); |
System.out.print("The Reverse of the number is "+ str.reverse()); |
}
import java.util.Scanner; |
Comments
Post a Comment