Chinaunix首页 | 论坛 | 博客

AAA

  • 博客访问: 18414
  • 博文数量: 33
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 330
  • 用 户 组: 普通用户
  • 注册时间: 2015-04-17 08:23
个人简介

好记性不如烂笔头,记录学习历程和随想云云,欢迎各位大虾拍砖

文章分类

全部博文(33)

文章存档

2015年(33)

我的朋友
最近访客

分类: C/C++

2015-05-04 21:05:37

【问题描述】

Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

【解题思路】

点击(此处)折叠或打开

  1. #define CACHE 256
  2. enum { h_unknown = 0, h_yes, h_no };
  3. unsigned char buf[CACHE] = {0, h_yes, 0};

  4. bool isHappy(int n) {
  5.     int sum = 0, x, nn;
  6.     if (n < CACHE) {
  7.         if (buf[n]) return 2 - buf[n];
  8.         buf[n] = h_no;
  9.     }
  10.  
  11.     for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;
  12.  
  13.     x = isHappy(sum);
  14.     if (n < CACHE) buf[n] = 2 - x;
  15.     return x;
  16. }

阅读(220) | 评论(0) | 转发(0) |
0

上一篇:Isomorphic Strings

下一篇:Count Primes

给主人留下些什么吧!~~