【202. Happy Number(LeetCode)】智慧并不产生于学历,而是来自对于知识的终生不懈的追求。这篇文章主要讲述202. Happy Number(LeetCode)相关的知识,希望能为你提供帮助。
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 class Solution { 2 public: 3int fang(int n) 4{ 5int sum = 0; 6while (n != 0) 7{ 8sum += (n % 10)*(n % 10); 9n = n / 10; 10} 11cout< < sum< < endl; 12return sum; 13} 14 15bool isHappy(int n) { 16int i=0; 17while (n!=1& & i< 100) 18{ 19n = fang(n); 20cout< < n< < endl; 21i++; 22} 23if (n == 1& & i< 100) 24{ 25return true; 26} 27if (i > = 100) 28return false; 29} 30 };
1 class Solution { 2 public: 3bool isHappy(int n) { 4unordered_map< int, bool> m; 5while (n != 1 & & !m.count(n)){ 6m[n] = true; 7int new_n = 0; 8while (n){ 9new_n += (n % 10)*(n % 10); 10n /= 10; 11} 12n = new_n; 13} 14return n == 1; 15} 16 };
推荐阅读
- android自己定义之 5.0 风格progressBar
- Android中颜色透明度
- 自适应网站设计对百度友好的关键(添加applicable-device标签(转))
- Android 中View仅仅能接收到ACTION_DOWN无法接收ACTION_MOVE和ACTION_UP解决的方法
- *Android 多线程下载 仿下载助手(改进版)
- Android Tangram模型(连淘宝天猫都在用的UI框架模型你一定要懂)
- 如何唯一的标识一台Android设备()
- 转自Android内存机制分析1——了解Android堆和栈
- Mybatis框架中Mapper文件传值参数获取。Mybatis