leetcode_c++:哈希: Happy Number(202)
2016-07-09 15:02
447 查看
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
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
算法
O(N)hash的方法
// // main.cpp // CplusplusTest // // Created by mijian on 16/7/1. // Copyright © 2016年 mijian. All rights reserved. // #include <iostream> #include <string> #include <vector> #include <map> #include <limits.h> #include <unordered_map> #include <sstream> #include<unordered_set> using namespace std; class Solution { public: bool isHappy(int n) { unordered_set<int> vis; while(vis.find(n)==vis.end()){ vis.insert(n); int tmp=0; while(n){ tmp+=(n%10)*(n%10); n/=10; } n = tmp; if(n==1) return true; } return false; } }; int main(){ Solution s; int n; for(n=0;n<10000;++n){ if(s.isHappy(n)) cout<<n<<", "; } return 0; }
相关文章推荐
- Android开发中内存、内部存储、外部存储详解
- iPad/iPhone登陆iOS Beta页提示"Your session has expired"解决办法
- [个人收藏]成为iOS顶尖高手,你必须来这里(这里有最好的开源项目和文章)
- Android EditText监听焦点事件
- react-native-webview-bridge使用问题
- Android 属性动画,补间动画,xml资源动画详解
- Android 基础 -------Activity
- Android中的自定义view和自定义属性TypedArray的使用
- [UnityShader3]光晕效果
- Android adb 命令备忘
- 漫谈android系统(4)bring up panel
- 漫谈android系统(4)bring up panel
- iOS开发英汉术语对照(三)
- (OK) Android命令行测试BT,WIFI,Sensor工作状态 — svc
- 慕课网实战—《用组件方式开发 Web App全站 》笔记一
- Android隐藏系统信息栏
- 又又一天的unity学习总结
- android studio 使用 subversion
- Android 文件夹中所有文件
- 深入理解iOS开发之RunLoop