A clear simple java solution, easy to figure out


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

  • 0
    K
    private int calculate(int n) {
    	String str = Integer.toString(n);
    	int sum,temp;
    	for (int i = 0; i<str.length(); i++) {
    		temp = Integer.parseInt(String.valueOf(str.charAt(i)));
    		sum += temp*temp;
    	}
    	return sum;
    }
    

    another way :)


  • 0
    S

    nice train of thought, but it cost more when transfer into string and deal with it


  • 0
    J

    charToInt can be easily written as

    int i = ch - '0'


  • 0
    S

    Great solution. Thanks.


Log in to reply
 

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