Java 程序将数字拆分为位数


2022 年 2 月 3 日, Learn eTutorial
3176

如何将数字拆分为位数?

我们可以使用模运算符将数字拆分为位数。假设 num=523,那么 num % 10 返回 3。因此,通过使用 while 循环,我们可以通过模 10 将数字拆分为位数,然后将数字除以 10 来移除最后一个数字(在获取该数字之后)。

split integer number into digits

如何使用 Java 实现这个数字拆分程序逻辑?

要解决这个 Java 程序,我们必须声明 Digit 类。声明整数变量 num、tmp、dgt、count。从用户读取数字到变量 num。将变量保存在临时变量 tmp 中,即 tmp=num。然后使用 while 循环检查 num > 0,如果为真,则计算 num=num/10,将 count 递增一;在这里,我们将获得用户输入数字的位数计数。

通过使用另一个 while 循环检查 tmp > 0,然后计算 dgt= tmp % 10,现在 dgt 包含数字的最后一个数字。使用 System.out.println 方法显示它。然后将 tmp/10 除以其余数字,并将其保存在 tmp 中。将 count 递减一,并重复这些步骤,直到 tmp 变为 0。

算法

步骤 1:使用 public 修饰符声明 Digit 类。

步骤 2:打开 main() 以启动程序,Java 程序执行从 main() 开始

步骤 3:将整数变量 num、tmp、dgt、count 声明为整数。将 count=0 设置为。

步骤 4:将数字读入变量 num

步骤 5:将 num 保存到 tmp

步骤 6:通过使用 while 循环检查 num > 0,执行步骤 7。在这里,我们获取插入数字中的位数。

步骤 7num=num/10,将 count 递增一。

步骤 8:通过使用另一个 while 循环检查 tmp > 0 并执行步骤 9 到 11。

步骤 9dgt= tmp % 10,显示count位置的数字是dgt

步骤 10:计算 tmp=tmp/10

步骤 11:将 count 递减一。

Java 源代码

                                          import java.util.Scanner;
public class Digit{
    public static void main(String args[]){
        int num, tmp, dgt,count=0;
     
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number:");
        num = sc.nextInt();
        sc.close();
        tmp = num;
    
        while(num> 0)
        {
            num= num/10;
            count++;
        }
        while(tmp> 0)
        {
            dgt=tmp % 10;
            System.out.println("The Digit at place "+count+" is: "+dgt);
            tmp = tmp/10;
            count--;
        }
    }
}
                                      

输出

Enter the number:500
The Digit at the place of  3 is: 0
The Digit at the place of  2 is: 0
The Digit at the place of  1 is: 5