簡體   English   中英

遍歷數字中的每個數字

[英]Iterate through each digit in a number

我正在嘗試創建一個程序來判斷給它的數字是否是“快樂數字”。 找到一個快樂的數字需要對數字中的每個數字進行平方,並將每個數字的平方的結果加在一起。

在 Python 中,你可以使用這樣的東西:

SQUARE[d] for d in str(n)

但是我找不到如何在 Java 中遍歷數字中的每個數字。 如您所知,我是新手,在 Java 文檔中找不到答案。

您可以使用模 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);事情Math.pow(charArray[i] - '0', 2.0);

我想知道哪種方法可以最快地將正數拆分為 Java 中的數字,字符串與模數

  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
  }

對比

  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.334 秒。 (在 Eclipse Neon 中運行的 64 位 Ubuntu 上的 Oracle Java 8)

所以實際上並不多,但我有點驚訝 String 更快

假設數字是一個整數,以:

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);
}

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

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

代替

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

此代碼返回符合您的描述的第一個數字(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++;
    }
}

您可以將整數轉換為字符串並遍歷字符串中的每個字符。 當你這樣做時,把那個字符變成一個整數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM