Java code to know when a number is Happy

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits in base-ten, and repeat the process until the number either equals 1 (where it will stay), or it loops endlessly in a cycle that does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers)[1].

package education.jtrainer.ishappy;

public class IsHappy {
    
    static int iteration=0;
    static private Boolean isHappy(String a){
        iteration++;
        System.out.println("iteration n."+iteration+" input value:"+a);
        int value=0;
        int size=a.length();
        int sum=0;
        for (int i=0;i<size;i++) {
            char element=a.charAt(i);
            int valueInt=Character.getNumericValue(element);
            sum=sum+valueInt*valueInt;
        }
        if (sum==1) return true;
        else {
            
            if (isUnHappy(sum)) return false;
            return(isHappy(Integer.toString(sum)));
        }
    }
    
    static private Boolean isUnHappy(int b){
        Integer[] unhappylist = new Integer[]{4, 16, 37, 58, 89, 145, 42, 20};
        for (int i=0;i<8;i++){
            if (b==unhappylist[i]){
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        if (isHappy("49").equals(Boolean.TRUE)){
            System.out.println("number is happy");
        }
        else {
            System.out.println("number is unhappy");
        }           
    }
}

Download from github:
https://github.com/jtrainer-education/HappyJava

References
[1] – https://en.wikipedia.org/wiki/Happy_number#cite_note-1

Leave a Reply

Your email address will not be published. Required fields are marked *