[leetcode] 202.Happy Number
2015-07-18 17:53
211 查看
题目:
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
题意:
判断一个数是否是happy number,将该数的每一位求平方,然后求和得到新的数字,如果是1那就是happy number。否则一直做下去,直到出现1或者这个求得的和已经出现过了。
思路:
使用一个set保存已经求得的和。
代码如下:
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
题意:
判断一个数是否是happy number,将该数的每一位求平方,然后求和得到新的数字,如果是1那就是happy number。否则一直做下去,直到出现1或者这个求得的和已经出现过了。
思路:
使用一个set保存已经求得的和。
代码如下:
class Solution { public: bool isHappy(int n) { if(n == 1)return true; unordered_set<int> nums; while(n != 1) { n = getRes(n); if(nums.find(n) != nums.end())return false; else nums.insert(n); } return true; } int getRes(int n) { int result = 0; while(n > 0) { int last = n % 10; result += last*last; n /= 10; } return result; } };
相关文章推荐
- Android新组件RecyclerView介绍,其效率更好
- Android新组件RecyclerView介绍,其效率更好
- Android学习资源(持续更新中)
- android 环境搭建中adk 位置找不到问题解决方案
- iOS中用正则表达式验证邮箱和手机号
- 如何解决:Android中 Error generating final archive: Debug Certificate expired on 10/09/18 16:30 的错误
- java日期格式的Object类型转换成String类型的方法
- 报错Error configuring application listener of class jdbc.ContextListener 解决办法之一
- OC学习笔记之-OC基础知识(类于对象)
- 微信公众号提交开发者提示token验证失败
- 【objective-c】字典快速转换为Model代码
- Weinre调试移动端页面
- android 项目的主要结构与详细讲解
- 基于mina的的android即时通信app
- 【Android】资源系列(一) -- 国际化(多语言)
- Android-PullToRefresh库实现上拉刷新下拉加载
- Android.mk详解
- android颜色对应的xml配置值,颜色表
- Android Support Design 中 CoordinatorLayout 与 Behaviors 初探
- Android自定义View研究(四) -- 在XML中定义View