leetcode 202 Happy Number(难易度:Easy)
来源:互联网 发布:皇家猫粮 知乎 编辑:程序博客网 时间:2024/06/05 17:06
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
代码:
bool isHappy(int n) { while (n > 6) {int next = 0;while (n) {next += (n % 10) * (n % 10);n /= 10;}n = next;}return n == 1;}
int digitSquareSum(int n) { int sum = 0, tmp; while (n) { tmp = n % 10; sum += tmp * tmp; n /= 10; } return sum;}bool isHappy(int n) { int slow, fast; slow = fast = n; do { slow = digitSquareSum(slow); fast = digitSquareSum(fast); fast = digitSquareSum(fast); } while(slow != fast); if (slow == 1) return 1; else return 0;}
原题地址:https://leetcode.com/problems/happy-number/
0 0
- leetcode 202 Happy Number(难易度:Easy)
- leetcode 171 Excel Sheet Column Number(难易度:Easy)
- leetcode 136 Single Number(难易度:Easy)
- leetcode 191 Number of 1 Bits(难易度:Easy)
- leetcode 009 Palindrome Number(难易度:Easy)
- [Leetcode 202, Easy] Happy Number
- 【LeetCode】(202)Happy Number(Easy)
- 【Leetcode】202-Happy Number【Java实现】【Easy】
- <LeetCode><Easy> 203 Happy Number
- LeetCode 202. Happy Number (Easy)
- leetcode 242 Valid Anagram(难易度:Easy)
- leetcode 258 Add Digits(难易度:Easy)
- leetcode 058 Length of Last Word(难易度:Easy)
- leetcode 234 Palindrome Linked List(难易度:Easy)
- leetcode 172 Factorial Trailing Zeroes(难易度:Easy)
- leetcode 125 Valid Palindrome(难易度:Easy)
- leetcode 100 Same Tree(难易度:Easy)
- leetcode 226 Invert Binary Tree(难易度:Easy)
- 前端文章
- 性能优化_JS篇
- Android 之 Handler 的使用(一)
- 网站推广成功之法—独占神话
- 依赖倒置原则
- leetcode 202 Happy Number(难易度:Easy)
- 大四上week2-4(抽象类,接口,Object类,扑克牌案例 )
- IMX6Solo启动流程-Linux 内核启动 一
- DataGridView和ListView比较
- Eclipse中Tomcat插件的使用说明
- 分冶法之归并排序
- Asynchttpclient的使用及请求与响应封装
- hdu1505city game dp
- 凌凯短信Webservice接口报错解决办法