反转数字的Java程序
反转一个数字意味着第一个位置的数字应该与最后一个数字交换,第二个数字将与倒数第二个数字交换,依此类推,直到中间元素,
要反转数字,应执行以下步骤:
- Take the number’s modulo by 10
- Multiply the reverse number by 10 and add modulo value into the reverse number.
- Divide the number by 10.
- Repeat above steps until number becomes zero.
我们可以使用两种方法在Java中反转一个数字。
1.使用While循环:
只需应用所讨论的步骤/算法,并在数字变为零时终止循环。
- 取数字的模数 10
- 将倒数乘以 10 并将模值添加到倒数中。
- 将数字除以 10。
- 重复上述步骤,直到数字变为零。
下面是上述方法的实现:
Java
// Java program to reverse a number
import java.io.*;
class GFG {
// Function to reverse the number
static int reverse(int n){
int rev = 0; // reversed number
int rem; // remainder
while(n>0){
rem = n%10;
rev = (rev*10) + rem;
n = n/10;
}
return rev;
}
// Driver Function
public static void main (String[] args) {
int n = 4526;
System.out.print("Reversed Number is "+ reverse(n));
}
}
Java
// Java program to reverse a number recursively
import java.io.*;
class GFG {
// stores reversed number
static int rev = 0;
// Function to reverse the number
static void reverse(int n){
if(n<=0)
return ;
int rem = n%10; // remainder
rev = (rev*10) + rem;
reverse(n/10);
}
// Driver Function
public static void main (String[] args) {
int n = 4526;
reverse(n);
System.out.print("Reversed Number is "+ rev);
}
}
输出
Reversed Number is 6254
2. 使用递归:
在递归中,最终的反向值将存储在全局“rev”变量中。请按照以下说明操作。
- If the number becomes zero then terminate the recursion, this will be the base condition.
- Take the modulo and add it with the ‘rev*10’ multiplying.
- Divide the number by 10 and call the reverse function on this number after updating it to number/10.
下面是递归方法的Java实现。
Java
// Java program to reverse a number recursively
import java.io.*;
class GFG {
// stores reversed number
static int rev = 0;
// Function to reverse the number
static void reverse(int n){
if(n<=0)
return ;
int rem = n%10; // remainder
rev = (rev*10) + rem;
reverse(n/10);
}
// Driver Function
public static void main (String[] args) {
int n = 4526;
reverse(n);
System.out.print("Reversed Number is "+ rev);
}
}
输出
Reversed Number is 6254