AC solution in Java


  • 4
    L
    public class Solution {
        public boolean isHappy(int n) {
            Set<Integer> seen = new HashSet<>();
            while (!seen.contains(n)) {
                seen.add(n);
                int sum = 0;
                while (n > 0) {
                    sum += (n % 10) * (n % 10);
                    n /= 10;
                }
                n = sum;
            }
            return seen.contains(1);
        }
    }

  • 0
    2

    you don't need to convert the number and put them into the list. Simply use % to get all the digit and add the square of them and return.


  • 0
    L

    Thank you for ur suggestion. I have edited the code.


Log in to reply
 

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