Iterate through each digit in a number

后端 未结 5 754
星月不相逢
星月不相逢 2020-12-15 07:41

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,

5条回答
  •  不知归路
    2020-12-15 07:57

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

提交回复
热议问题