# O(1) space Java solution

• ``````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 ;
}
}``````

• This is a bit similar to finding if a singly linked list has a cycle.

• Do we need to consider the 'invalid input' for the code here?

Sorry, I am quick new for this leetcode. :)

• no but you need to consider edge cases e.g. list is empty number is 0 so on and so forth
usually the question will state either explicitly or implicitly the input range.

• Very interesting solution. But sometimes it needs to loop multiple times to find a match. So I think the HashSet solution is relatively quicker.

• What if the loop has more than two numbers?

• This post is deleted!

• Can anyone help analyze the time complexity of this algorithm? Thanks!

• how to make sure the loop end with x==y ?it may be endless?

• how to make sure the loop end with x==y ?it may be endless?

• +1
why the loop is 3？

• Year,quite agree with you.
Two feet point used here can save memory

• +1 I'm confused too

• What if the input is 12? 12 is not an happy number, its loop starts with 4, but by this algorithm, 12 will be judged as an happy number.

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

• good idea. one thing I wanna point out is that the space complexity of hashset impl is low(it's bounded).

• 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 2-9 have no square subs,give me your advice.

• This post is deleted!

• This post is deleted!

• This post is deleted!

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