💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# Java 程序:使用`for`,`while`和递归来反转一个数字 > 原文: [https://beginnersbook.com/2014/01/java-program-to-reverse-a-number/](https://beginnersbook.com/2014/01/java-program-to-reverse-a-number/) 在 Java 中有三种方法可以反转数字。 1)[使用`while`循环](#using-while) 2)[使用`for`循环](#using-for) 3)[使用递归](#using-recursion) 4)[用户互动的反转数字](#demo) ### 程序 1:使用`while`循环反转一个数字 程序将提示用户输入数字,然后使用`while`循环反转相同的数字。 ```java 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); } } ``` 输出: ```java Input your number and press enter: 145689 Reverse of input number is: 986541 ``` ### 程序 2:使用`for`循环反转一个数字 ```java 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); } } ``` 输出: ```java Input your number and press enter: 56789111 Reverse of specified number is: 11198765 ``` ### 程序 3:使用递归反转数字 ```java 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(); } } ``` 输出: ```java Input your number and press enter: 5678901 Reverse of the input number is:1098765 ``` **示例:反转已经初始化的数字** 在上述所有程序中,我们正在提示用户输入数字,但是如果不想要用户交互部分并且想要反转初始化数字那么这就是你能行的。 ```java 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); } } ``` 输出: ```java Reverse of specified number is: 987654321 ```