Problem:
Design an algorithm that accepts a positive integer and reverses the order of its digits.
Solution:
package com.myprograms;
import java.util.Scanner;
public class ReverseTheNumber {
public static void main(String[] args) {
System.out.println("the reverse number is " + reverseTheNumber(getTheNumber()));
}
public static int getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter the n value");
int n = s.nextInt();
s.close();
return n;
}
private static int reverseTheNumber(int n){
int reverseNumber = 0;
while(n > 0){
reverseNumber = (reverseNumber * 10) + n % 10;
n = n/10;
}
return reverseNumber;
}
}
Output:
enter the n value
27953
the reverse number is 35972
Design an algorithm that accepts a positive integer and reverses the order of its digits.
Solution:
package com.myprograms;
import java.util.Scanner;
public class ReverseTheNumber {
public static void main(String[] args) {
System.out.println("the reverse number is " + reverseTheNumber(getTheNumber()));
}
public static int getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter the n value");
int n = s.nextInt();
s.close();
return n;
}
private static int reverseTheNumber(int n){
int reverseNumber = 0;
while(n > 0){
reverseNumber = (reverseNumber * 10) + n % 10;
n = n/10;
}
return reverseNumber;
}
}
Output:
enter the n value
27953
the reverse number is 35972
No comments:
Post a Comment