my solution in java with 2ms


  • 0
    P
    public class Solution {
        public boolean isHappy(int n) {
            int sum = 0;
            boolean flag = true;
            int[] unhappy = new int[] {4, 16, 37, 58, 89, 145, 42, 20};
            while (sum != 1) {
                sum = 0;
                while (n > 0) {
                    sum += (n % 10) * (n % 10);
                    n /= 10;
                }
                for (int i = 0; i < unhappy.length; i++) {
                    if (sum == unhappy[i]) {
                        flag = false;
                        break;
                    }
                }
                if (!flag) {
                    break;
                }
                n = sum;
            }
            return flag;
        }
    }

Log in to reply
 

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