202 Happy Number
2015-08-08 16:52
281 查看
题目链接:https://leetcode.com/problems/happy-number/
题目:
解题思路:
- 对数字 n 的每一位平方求和为 sum。
- 若 sum 为 1,返回 true;
- 若 sum 不为1,判断 list 中是否有该键
- 没有,就添加到 list 中
- 有,则说明正在经历循环,跳出循环结束程序
注意:
无法确定是第几次对数字位数求出的和进入了循环。因而不可以假定第一次求和产生的数为loop的第一个数。也不可以假定求和产生的最大最小数为loop中的数。
一开始只想到用 HashMap 来判断是否有重复的数,其实也可以选用别的数据结构,例如 arrayList,LinkedList 等。毕竟只用判断当前求出的和是否过去已经出现过,而不必用知道它出现了几次。实际上 map 的值的部分空间被浪费了。
题目:
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
解题思路:
- 对数字 n 的每一位平方求和为 sum。
- 若 sum 为 1,返回 true;
- 若 sum 不为1,判断 list 中是否有该键
- 没有,就添加到 list 中
- 有,则说明正在经历循环,跳出循环结束程序
注意:
无法确定是第几次对数字位数求出的和进入了循环。因而不可以假定第一次求和产生的数为loop的第一个数。也不可以假定求和产生的最大最小数为loop中的数。
一开始只想到用 HashMap 来判断是否有重复的数,其实也可以选用别的数据结构,例如 arrayList,LinkedList 等。毕竟只用判断当前求出的和是否过去已经出现过,而不必用知道它出现了几次。实际上 map 的值的部分空间被浪费了。
public class Solution { public boolean isHappy(int n) { if(n == 0) return false; if(n == 1) return true; ArrayList<Integer> list = new ArrayList(); boolean res = false; while(true) { int sum = 0; while(n != 0) { int p = n % 10; n = n / 10; sum += p * p; } if(sum == 1) { res = true; break; } if(list.contains(sum)) break; list.add(sum); n = sum; } return res; } }
400 / 400 test cases passed. Status: Accepted Runtime: 220 ms
相关文章推荐
- IOS7中自动计算label的宽度和高度的方法
- wget突破cookie限制--用wget批量下载中国联通沃商店app
- Android数据手册01:Android颜色码制表
- Android四大组件之BroadCast(续)
- cocos2d-x综述(源自cocos2d-x中文网)
- 每天学点java—Object类
- Android widget 之RemoteView
- 《learn objective-c on the Mac for OS X and IOS》<译名>《objective-C基础教程》
- iOS8的新特性(MOdel笔记)
- Swift学习笔记之字符串(二)
- Android搜索框(保存历史记录和自动匹配)带有ScrollView嵌套ListView阻尼效果
- Swift构造函数(Initializer)和析构函数(Deinitializer)
- IntentService与Service用法区别
- 附两个自己认为比较重要的链接地址(移动端的position:fixed,flexbox实现垂直居中布局)
- android kl文件
- Android性能优化典范 - 第2季
- Android ANR产生原因和解决办法
- android中的任务栈和启动模式的总结
- Android之GridView横向左右滚动
- Android EventBus现实 听说你out该