【问题标题】:How to get the digits of an integer and store it into an array? [closed]如何获取整数的位数并将其存储到数组中? [关闭]
【发布时间】:2022-01-20 05:57:28
【问题描述】:

我对编程很陌生。我在 Programming Praxis 中发现了这个有趣的问题,并被困在如何获取整数的数字并将它们存储到数组中。

老实说,我不知道从哪里开始,我想学习如何在 Java 中做到这一点。

如果您有兴趣,这是我正在处理的问题的代码。

public class MyClass {
    public static void main(String args[]) {
    // Determine all three-digit numbers N having the property that N is divisible by 11, and N/11 is equal to the sum of the squares of the digits of N.
    int num = 100;
    int square_sum = 0;
    int digit1 = 0;
    int digit2 = 0;
    int digit3 = 0;
    while (num <= 999){
        
        if (num % 11 == 0) { //if remainder == 0; the number is divisible by 11// 
           
            // We need to get the digits of int "num" and square them // 
            int arrayDigits[] = new int[3];

            } else 
                num++;
        }
    }
}

【问题讨论】:

标签: java arrays


【解决方案1】:

这是一个示例:(与您的代码不匹配,因此您必须考虑一下)

 int[] arr = new int[] {100, 123, 21};

//get first index of your array
        int a = arr[0];

//turn it into a string
        String b = String.valueOf(a);

//split the string
        String[] c = b.split("");

        System.out.println(c[0]);

通过这种方式,您的String[] c 是一个字符串数组,您可以像访问普通数组一样访问这些值

【讨论】:

    【解决方案2】:
    public static void main(String args[]) {
        // Determine all three-digit numbers N having the property that N is divisible by 11, and N/11 is equal to the sum of the squares of the digits of N.
        int num = 100;
        int square_sum = 0;
        int digit1 = 0;
        int digit2 = 0;
        int digit3 = 0;
        while (num <= 999) {
            if (num % 11 == 0) { //if remainder == 0; the number is divisible by 11//
                // We need to get the digits of int "num" and square them //
                int arrayDigits[] = new int[3];
                digit1 = num % 10;
                digit2 = (num / 10) % 10;
                digit3 = (num / 100) % 10;
                square_sum = digit1 * digit1 + digit2 * digit2 + digit3 * digit3;
                if ((num / 11) == square_sum) {
                    System.out.println(num);
                }
            }
            num++;
        }
    }
    

    如果你想得到 int "num" 的每个数字

    digit1 = num % 10;
    digit2 = (num / 10) % 10;
    digit3 = (num / 100) % 10;
    

    【讨论】:

    • 你能edit你的答案解释为什么这应该回答这个问题以及你改变了什么吗?
    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2011-11-05
    • 2018-01-19
    • 2019-12-03
    • 2013-05-16
    • 2023-01-19
    • 2021-12-02
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多