Simple Java Solution


  • 0
    L
    public class Solution {
        public boolean isHappy(int n) {
            Set<Integer> viewed = new HashSet<>();
            
            int result = next(n);
            
            while (result != 1 && !viewed.contains(result)) {
                viewed.add(result);
                result = next(result);
            }
            
            return result == 1;
        }
        
        private int lastDigit(int n) {
            return n % 10;
        }
        
        private int next(int n) {
            int current = n;
            int result = 0;
            
            while (current != 0) {
                result += (int) Math.pow(lastDigit(current), 2);
                current = current / 10;
            }
            return result;
        }
    }
    

    I was going for readability over efficiency.


Log in to reply
 

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