Wednesday 30 January 2013

7733. Happy Numbers I Problem code: HPYNOS

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())

2 comments:

  1. #include
    int 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;
    }

    ReplyDelete
    Replies
    1. 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