Share my accepted Java solution!


  • 26
    I
    public class Solution {
        public boolean isHappy(int n) {
            HashSet<Integer> set = new HashSet<Integer>();
            set.add(n);
            while (n != 1) {
                int result = 0;
                while (n != 0) {
                    result += Math.pow(n % 10, 2);
                    n /= 10;
                }
                if (set.contains(result)) {
                    return false;
                }
                set.add(result);
                n = result;
            }
            return true;
        }
    }

  • -2
    4

    private static boolean isHappyNumber(int num) {

        int sum = 0;
        while (num > 0) {
            sum = sum + (num % 10) * (num % 10);
            num = num / 10;
    
            if (num <= 0) {
                if (sum == 1) return true;
                else if (sum < 10) return false;
                else {
                    num = sum;
                    sum = 0;
                }
            }
        }
    
        return false;
    }

  • 0
    L

    I like your solution. To make even simpler the the add() method on a set returns true if it an element is successfully invited, otherwise false. So a simple if(!set.add(result))false; , would have saved you a few lines.


Log in to reply
 

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