leetcode 202 Happy Number
2016-06-20 21:33
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
Credits:
Special thanks to @mithmatt and @ts for
adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution {
public:
bool isHappy(int n) {
if(n==1) return true;
map<int, int> exits;
int cnt = 1, sum = 0;
while(exits.count(n)==0) {
exits
= 1;
if(n==1) return true;
while(n > 0) {
sum += (n%10)*(n%10);
n = n / 10;
}
n = sum;
sum = 0;
}
return false;
}
}
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
Credits:
Special thanks to @mithmatt and @ts for
adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution {
public:
bool isHappy(int n) {
if(n==1) return true;
map<int, int> exits;
int cnt = 1, sum = 0;
while(exits.count(n)==0) {
exits
= 1;
if(n==1) return true;
while(n > 0) {
sum += (n%10)*(n%10);
n = n / 10;
}
n = sum;
sum = 0;
}
return false;
}
}
相关文章推荐
- ios学习路线—Objective-C(nil与release的区别与用法)
- iOS学习- 23 Core Data by Tutorials - CH03
- Android Studio教程--Android Studio 2.1安装与配置
- 安卓中计算 TextView 的宽高、打点
- 移动开发,touchstart轮播图,移动端拖拽应用
- git的创建新项目的使用
- Android-Android studio 出现 Error: NDK integration is deprecated in the current plugin. 问题解决
- 常用iOS的第三方框架
- iOS 判断字符串中含有某个字符串
- Ojective-C入门请读
- iOS_逆向_使用class dump导出头文件
- android 连接 wcf rest注意点
- iOS_逆向_使用dumpdecrypted砸壳
- App 版本信息等
- iOS webView加载网页失败,浏览器成功的原因,以及读取cookie
- 不同厂家的电脑进入bios的快捷键整理汇总
- Android(Java)之多线程结果返回——Future 、FutureTask、Callable、Runnable
- LruCache详解之 Android 内存优化
- "xxx" is not translated in "en" (English)
- android中自定义dialog的使用方法简介