Iterate through each digit in a number

后端 未结 5 746
星月不相逢
星月不相逢 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:46

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

提交回复
热议问题