Accepted Solution Using String


  • 0
    O
    class Solution {
        public boolean isHappy(int n) {
          return calculate(n, 0);
        }
        
        public boolean calculate(int n, int numIterations){
            if(numIterations > 100) return false;
            if(n == 1) return true;
            int sum = 0;
            
            String number =  String.valueOf(n);
            int i= 0;
            while(i < number.length()){
                int intAgain = Integer.parseInt(number.substring(i,i+1)); 
                sum += Math.pow(intAgain, 2);
                i ++;
            }
            numIterations ++;
            boolean result = calculate(sum, numIterations);
            return result; 
        }
    }
    

Log in to reply
 

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