202. Happy Numbe
来源:互联网 发布:51单片机如何烧录程序 编辑:程序博客网 时间:2024/06/05 08:55
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
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
这道题和 258.Add Dighits 的第一种解法很像,只不过上一道题的终止条件是小于10,而这道题的终止条件是无限循环(loops endlessly),也就是再循环过程中出现了以前出现的数字,所以这道题就简化成:判断是否出现过这个数字。
通常采用的方法是:
创建一个set或者hash_set函数,在这里我用的是CODEBLOCKS,如果用hash_set,会出现
error: 'hash_set' was not declared in this scope
的错误,VS2013上可以。
在这里我用的是set
#include <set>#include <iostream>using namespace std; bool isHappy(int n) { set<int> set; while(n!=1){ int sum = 0; while(n>0){ sum += (n % 10) * (n % 10); n = n / 10; } if(set.find(sum) != set.end()) //循环终止条件 { cout<<2<<endl; return false; } else { set.insert(sum); } n = sum; } cout<<1<<endl; return true; }int main(){ int n; cin>>n; isHappy(n); return 0;}
- 然后就是大神级别的方法了,在DISSCUS中看到如下方法,复杂度只有o(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;}
- 202. Happy Numbe
- Happy Numbe
- Single Numbe
- [LeetCode]136.Single Numbe
- HDU 1018 big numbe
- LeetCode 9.Palindrome Numbe
- 202. Happy Number
- [LeetCode]202.Happy Number
- 【LeetCode】202.happy number
- LeetCode 202. Happy Number
- [leetcode] 202.Happy Number
- 【leetcode】202. Happy Number
- 202.Happy Number
- [leetcode] 202. Happy Number
- 202. Happy Number LeetCode
- 202. Happy Number
- leetCode 202. Happy Number
- 202. Happy Number
- Farmer Bill's Problem
- css reset 重置样式 html5
- Shader 学习笔记 20160501
- python正则表达式指南
- 千里之行,始于足下
- 202. Happy Numbe
- 理解Tomcat(一) 利用Digester解析xml文件
- 2016/5/1
- 两分钟看懂空格替换
- jsp的几种注释
- highcharts 图表插件与Struts2结合应用,用图表直观展现后台数据分析结果
- wampserver配置教程
- Hdu 1548 A strange lift
- Centos 6.5 FTP 文件服务器搭建