【问题】 将一个整数逆序输出。
【思路】 有三种方法可以将一个数逆序输出:
1)使用while循环
2)使用for循环
3)使用递归
【代码】
程序1:使用while循环
import java.util.Scanner;
class ReverseNumberWhile
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
System.out.println("Input your number and press enter: ");
//This statement will capture the user input
Scanner in = new Scanner(System.in);
//Captured input would be stored in number num
num = in.nextInt();
//While Loop: Logic to find out the reverse number
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
System.out.println("Reverse of input number is: "+reversenum);
}
}
输出结果:
Input your number and press enter:
145689
Reverse of input number is: 986541
程序2:使用for循环
import java.util.Scanner;
class ForLoopReverseDemo
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
System.out.println("Input your number and press enter: ");
//This statement will capture the user input
Scanner in = new Scanner(System.in);
//Captured input would be stored in number num
num = in.nextInt();
/* for loop: No initialization part as num is already
* initialized and no increment/decrement part as logic
* num = num/10 already decrements the value of num
*/
for( ;num != 0; )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
System.out.println("Reverse of specified number is: "+reversenum);
}
}
输出结果:
Input your number and press enter:
56789111
Reverse of specified number is: 11198765
程序3:使用递归
import java.util.Scanner;
class RecursionReverseDemo
{
//A method for reverse
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.print(number % 10);
//Method is calling itself: recursion
reverseMethod(number/10);
}
}
public static void main(String args[])
{
int num=0;
System.out.println("Input your number and press enter: ");
Scanner in = new Scanner(System.in);
num = in.nextInt();
System.out.print("Reverse of the input number is:");
reverseMethod(num);
System.out.println();
}
}
输出结果:
Input your number and press enter:
5678901
Reverse of the input number is:1098765
当然,如果待逆序的这个数事先已经初始化了,就不用从键盘输入了,如:
class ReverseNumberDemo
{
public static void main(String args[])
{
int num=123456789;//不从键盘输入,直接初始化为一个整数值。
int reversenum =0;
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
System.out.println("Reverse of specified number is: "+reversenum);
}
}