202. Happy Number
来源:互联网 发布:计算圆周率的算法 编辑:程序博客网 时间:2024/06/06 05:45
202. 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
1*1 + 9*9 = 82
8*8 + 2*2 = 68
6*6 + 8*8 = 100
1*1 + 0*0 + 0*0 = 1
Analysis:
这个博客写的很好:《[LeetCode] Happy Number 快乐数》http://www.cnblogs.com/grandyang/p/4447233.html
Source Code(C++):
#include <iostream>#include <algorithm>#include <vector>using namespace std;class Solution {public: bool isHappy(int n) { if (n<1) { return false; } else { vector<int> v; v.push_back(n); while(n != 1) { int sum = 0; while(n>0) { sum += (n%10)*(n%10); n /= 10; } n=sum; if (find(begin(v), end(v), n) != end(v)) { //之前出现过这个数,则进入无限循环 return false; } v.push_back(n); } return true; } }};int main() { Solution sol; cout << sol.isHappy(11); return 0;}
0 0
- 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
- 202. Happy Number
- 202. Happy Number
- [LeetCode]202. Happy Number
- leetcode 202. Happy Number
- 202. Happy Number
- 202. Happy Number
- Spring事务的传播行为和隔离级别
- 使用diskpart命令修复U盘分区
- PAT乙级—1038. 统计同成绩学生(20)-native
- URAL 1994 The Emperor's plan(dp、期望)
- 深入理解JVM内幕:从基本结构到Java 7新特性
- 202. Happy Number
- java学习、java入门我为什么要学习Java EE?
- oracle linux 5.9 不支持 acfs 文件系统 怎么解决呢?
- Android RecyclerView基本使用
- #码神心得_04# 基本数据类型转换
- 使用HTTP协议访问网络
- Gerrit 服务器搭建
- Android操作db的坑
- 算法之希尔排序