Squares = dict([(m, int(m)**2) for m in "0123456789"])
def is_happy(n):
s = []
count=0
while n not in s:
if n==1:
return count
s.append(n)
n = sum(Squares[digits] for digits in str(n))
count +=1
return -1
print is_happy(input())
def is_happy(n):
s = []
count=0
while n not in s:
if n==1:
return count
s.append(n)
n = sum(Squares[digits] for digits in str(n))
count +=1
return -1
print is_happy(input())
#include
ReplyDeleteint main()
{
unsigned long long N,sum=0,temp,count=0;
int rem;
scanf("%llu",&N);
temp=N;
while(sum!=1 && sum!=2 && sum!=3 && sum!=4 && sum!=5 && sum!= 6 && sum!=8 && sum!=9)
{
sum=0;
while(temp!=0)
{
rem=temp%10;
sum=sum+(rem*rem);
temp=temp/10;
}
temp=sum;
count++;
}
if(sum==1)
printf("%llu\n",count);
else
printf("-1\n");
return 0;
}
Nice approach. The brownie point in this solution is that U haven't used Hashset , So those Who are newbie to hashing can too attempt this.
Delete