Java AC solution


  • 0
    E

    Basic idea is also use a set to control the loop

     public boolean isHappy(int n) {
        if (n == 1) {
            return true;
        } 
        Set<Integer> set = new HashSet<>(); 
        while (!set.contains(n)) {
            set.add(n);
            String num = String.valueOf(n);
            char[] nums = num.toCharArray();
            int new_num = 0;
            for (int i = 0; i < nums.length; i++) {
              new_num += (nums[i] - '0') * (nums[i] - '0');        
            }
            if (new_num == 1) {
                return true;
            }
            n = new_num;
        }
        return false;
        
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.