迭代数字中的每个数字

发布于 2024-10-18 02:51:03 字数 281 浏览 6 评论 0原文

我正在尝试创建一个程序,该程序可以判断给定的数字是否是“快乐数字”。要找到一个快乐的数字,需要对数字中的每个数字进行平方,然后将每个数字的平方的结果相加。

在Python中,你可以使用这样的东西:

SQUARE[d] for d in str(n)

但我找不到如何在Java中迭代数字中的每个数字。正如您所知,我是新手,在 Java 文档中找不到答案。

I am trying to create a program that will tell if a number given to it is a "Happy Number" or not. Finding a happy number requires each digit in the number to be squared, and the result of each digit's square to be added together.

In Python, you could use something like this:

SQUARE[d] for d in str(n)

But I can't find how to iterate through each digit in a number in Java. As you can tell, I am new to it, and can't find an answer in the Java docs.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

楠木可依 2024-10-25 02:51:03

您可以使用模 10 运算来获取最右边的数字,然后将该数字除以 10 以获得下一个数字。

long addSquaresOfDigits(int number) {
    long result = 0;
    int tmp = 0;
    while(number > 0) {
        tmp = number % 10;
        result += tmp * tmp;
        number /= 10;
    }
    return result;
}

您还可以将其放入字符串中,然后将其转换为 char 数组,然后迭代它,执行类似 Math.pow(charArray[i] - '0', 2.0); 的操作

You can use a modulo 10 operation to get the rightmost number and then divide the number by 10 to get the next number.

long addSquaresOfDigits(int number) {
    long result = 0;
    int tmp = 0;
    while(number > 0) {
        tmp = number % 10;
        result += tmp * tmp;
        number /= 10;
    }
    return result;
}

You could also put it in a string and turn that into a char array and iterate through it doing something like Math.pow(charArray[i] - '0', 2.0);

羞稚 2024-10-25 02:51:03

我想知道在 Java 中哪种方法能最快地将正数分解为数字,字符串 vs 模数

  public static ArrayList<Integer> splitViaString(long number) {

    ArrayList<Integer> result = new ArrayList<>();
    String s = Long.toString(number);

    for (int i = 0; i < s.length(); i++) {
      result.add(s.charAt(i) - '0');
    }
    return result; // MSD at start of list
  }

vs

  public static ArrayList<Integer> splitViaModulo(long number) {

    ArrayList<Integer> result = new ArrayList<>();

    while (number > 0) {
      int digit = (int) (number % 10);
      result.add(digit);
      number /= 10;
    }
    return result; // LSD at start of list
  }

通过传递 Long.MAX_VALUE 10,000,000 次来测试每个方法,字符串版本花费了 2.090 秒,模数版本花费了 2.090 秒版本 2.334 秒。 (在 Eclipse Neon 中运行的 64 位 Ubuntu 上的 Oracle Java 8)

所以实际上并没有很多,但令我有点惊讶的是 String 更快

I wondered which method would be quickest to split up a positive number into its digits in Java, String vs modulo

  public static ArrayList<Integer> splitViaString(long number) {

    ArrayList<Integer> result = new ArrayList<>();
    String s = Long.toString(number);

    for (int i = 0; i < s.length(); i++) {
      result.add(s.charAt(i) - '0');
    }
    return result; // MSD at start of list
  }

vs

  public static ArrayList<Integer> splitViaModulo(long number) {

    ArrayList<Integer> result = new ArrayList<>();

    while (number > 0) {
      int digit = (int) (number % 10);
      result.add(digit);
      number /= 10;
    }
    return result; // LSD at start of list
  }

Testing each method by passing Long.MAX_VALUE 10,000,000 times, the string version took 2.090 seconds and the modulo version 2.334 seconds. (Oracle Java 8 on 64bit Ubuntu running in Eclipse Neon)

So not a lot in it really, but I was a bit surprised that String was faster

榕城若虚 2024-10-25 02:51:03

假设数字是一个整数:

int num = 56;
String strNum = "" + num;
int strLength = strNum.length();
int sum = 0;

for (int i = 0; i < strLength; ++i) {
  int digit = Integer.parseInt(strNum.charAt(i));
  sum += (digit * digit);
}

Assuming the number is an integer to begin with:

int num = 56;
String strNum = "" + num;
int strLength = strNum.length();
int sum = 0;

for (int i = 0; i < strLength; ++i) {
  int digit = Integer.parseInt(strNum.charAt(i));
  sum += (digit * digit);
}
习ぎ惯性依靠 2024-10-25 02:51:03

在上面的例子中我们可以使用:

int digit = Character.getNumericValue(strNum.charAt(i));

代替

int digit = Integer.parseInt(strNum.charAt(i));

In the above example we can use:

int digit = Character.getNumericValue(strNum.charAt(i));

instead of

int digit = Integer.parseInt(strNum.charAt(i));
孤芳又自赏 2024-10-25 02:51:03

您可以将整数转换为字符串并迭代字符串中的每个字符。当你这样做时,将该字符转换为整数

You can turn the integer into a string and iterate through each char in the string. As you do that turn that char into an integer

时光病人 2024-10-25 02:51:03

此代码返回第一个符合您的描述的数字(1 之后)。

public static void main(String[] args) {
    int i=2;
    // starting the search at 2, since 1 is also a happy number
    while(true) {
        int sum=0;
        for(char ch:(i+"").toCharArray()) { // casting to string and looping through the characters.
            int j=Character.getNumericValue(ch);
            // getting the numeric value of the current char.
            sum+=Math.pow(j, j);
            // adding the current digit raised to the power of itself to the sum.
        }
        if(sum==i) {
            // if the sum is equal to the initial number
            // we have found a number that fits and exit.
            System.out.println("found: "+i);
            break;
        }
        // otherwise we keep on searching
        i++;
    }
}

This code returns the first number (after 1) that fits your description.

public static void main(String[] args) {
    int i=2;
    // starting the search at 2, since 1 is also a happy number
    while(true) {
        int sum=0;
        for(char ch:(i+"").toCharArray()) { // casting to string and looping through the characters.
            int j=Character.getNumericValue(ch);
            // getting the numeric value of the current char.
            sum+=Math.pow(j, j);
            // adding the current digit raised to the power of itself to the sum.
        }
        if(sum==i) {
            // if the sum is equal to the initial number
            // we have found a number that fits and exit.
            System.out.println("found: "+i);
            break;
        }
        // otherwise we keep on searching
        i++;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文