public class Solution {
public boolean isHappy(int n) {
int x = n;
int y = n;
while(x>1){
x = cal(x) ;
if(x==1) return true ;
y = cal(cal(y));
if(y==1) return true ;
if(x==y) return false;
}
return true ;
}
public int cal(int n){
int x = n;
int s = 0;
while(x>0){
s = s+(x%10)*(x%10);
x = x/10;
}
return s ;
}
}
O(1) space Java solution


For those who might be interested, Here is my proof of why such an algorithm is mathematically valid in the first place.

public boolean isHappy(int n) {
int x = n;
while(x>1){
x = cal(x) ;
if(x == 1) return true ;
if(1 < x && x < 10)
return false;
}
return true ;
}
public int cal(int n){
int x = n;
int s = 0;
while(x>0){
s += (x%10)*(x%10);
x /= 10;
}
return s ;
}I think we don`t need variable y,cause int 29 have no square subs,give me your advice.