少年击剑更吹箫,剑气箫心一例消。这篇文章主要讲述[LeetCode] Happy Number相关的知识,希望能为你提供帮助。
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
非快乐数有以下的特性:所有不快乐数的数位平方和计算,最後都会进入 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的循环中。
所以外层循环:判断是否为快乐数和非快乐数。内层循环对n进行快乐数分解计算。
class Solution { public: bool isHappy(int n) { while (n != 1 & & n != 4) { int sum = 0, tmp = 0; while (n != 0) { tmp = n % 10; sum += tmp * tmp; n /= 10; } n = sum; } return n == 1; } }; // 3 ms
推荐阅读
- thisapply/callbind闭包函数变量复制
- yarn application ID 增长达到10000后
- win8系统关机提示”winlogon.exe没有磁盘“如何处理
- win8系统任务管理器需要很长时间才能打开怎样办
- Win8专业版系统关闭锁屏技巧的详细图文详细教程
- win8系统怎样进入dos界面?进入win8系统dos界面的3大办法
- win8系统怎样创建局域网完成文件共享【图文】
- win8设置系统怎样安装虚拟机?win8安装虚拟机的办法
- 怎样初始化让win8.1系统回到最初状态