在 Java 中反转整数
Sheeraz Gul
2023年1月30日
2022年4月27日
本教程将演示如何在不使用数组的情况下在 Java 中反转整数。
在不使用数组的情况下反转整数时,我们需要遵循三个步骤。
-
使用模 (%) 运算符查找整数的余数。
-
将变量
reverse
乘以 10,然后将其与余数相加。 -
将数字除以 10。
在 Java 中使用递归来反转整数
递归是使用模数和除法运算符反转整数的最简单方法。
例子:
import java.util.Scanner;
public class Reverse_Recursion{
//Create a method to reverse a number using recursion
public static void Recursion_reverse(int input_number){
if (input_number < 10){
//If the number is less then 10 then no need to reverse
System.out.println(input_number);
return;
}
else{
System.out.print(input_number % 10);
Recursion_reverse(input_number/10);
}
}
public static void main(String args[]){
System.out.print("Enter the Integer you want to Reverse: ");
Scanner input_num = new Scanner(System.in);
int input_number = input_num.nextInt();
System.out.print("The reverse of the given number using recursion is: ");
Recursion_reverse(input_number);
}
}
输出:
Enter the Integer you want to Reverse: 1234567890
The reverse of the given number using recursion is: 0987654321
在 Java 中使用 while
循环反转整数
要使用 while
循环反转整数,我们必须遵循提到的所有三个步骤。
例子:
import java.util.Scanner;
public class Reverse_While{
public static void main(String args[]){
System.out.print("Enter the Integer you want to Reverse: ");
Scanner input_num = new Scanner(System.in);
int input_number = input_num.nextInt();
int reverse_number = 0;
while(input_number != 0){
int remainder_number = input_number % 10;
reverse_number = reverse_number * 10 + remainder_number;
input_number = input_number/10;
}
System.out.println("The reverse of the given number using while loop is: " + reverse_number);
}
}
输出:
Enter the Integer you want to Reverse: 123456789
The reverse of the given number using while loop is: 987654321
在 Java 中使用 for
循环反转整数
for
循环也类似于 while
循环反转整数。
这次让我们尝试反转一个负整数。
例子:
import java.util.Scanner;
public class Reverse_For{
public static void main(String args[]) {
System.out.print("Enter the Integer you want to Reverse: ");
Scanner input_num = new Scanner(System.in);
int input_number = input_num.nextInt();
int reverse_number = 0;
for( ;input_number != 0; input_number=input_number/10){
int remainder_number = input_number % 10;
reverse_number = reverse_number * 10 + remainder_number;
}
System.out.println("The reverse of the given number using while loop is: " + reverse_number);
}
}
Enter the Integer you want to Reverse: -123456789
The reverse of the given number using while loop is: -987654321
Author: Sheeraz Gul
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook