LeetCode Happy Number
2015-07-23 06:38
441 查看
原题链接在这里:https://leetcode.com/problems/happy-number/
思路就是用HashSet 存储过往的和,若是遇见了相同的和,则表示出现了无限循环,没有happy number。
Note: 1. Math.pow()的argument 和 return value 都是 double 型,返回时要注意cast。
2. ^ operator stands for XOR - exclusive OR, 不是指数相乘,今后要注意。
3. 遍历一个数字的每一位就用下面的代码:
AC Java:
思路就是用HashSet 存储过往的和,若是遇见了相同的和,则表示出现了无限循环,没有happy number。
Note: 1. Math.pow()的argument 和 return value 都是 double 型,返回时要注意cast。
2. ^ operator stands for XOR - exclusive OR, 不是指数相乘,今后要注意。
3. 遍历一个数字的每一位就用下面的代码:
while(n!=0){ int digit = n%10; n = n/10; }
AC Java:
public class Solution { public boolean isHappy(int n) { if(n<=0) return false; HashSet hs = new HashSet(); while(!hs.contains(n)){ if(n == 1) return true; hs.add(n); int sum = 0; while(n!=0){ sum+=(int)Math.pow(n%10,2); //Math.pow will return a double variable, So we need to cast it. n = n/10; } n = sum; } return false; } }
相关文章推荐
- LeetCode Happy Number
- 读书笔记 day1:The design of approximation algorithms
- cocos2d-x 入门之Director,SceneLayer,Sprite
- iOS开发怎么定位问题出错的代码位置
- android开发变声器
- Unity3D之文件读写文件
- cocos2d-x 入门之初次使用
- IOS 逆向工程之砸壳
- 直接拿来用!最火的android开源项目(一)
- iOS开发-Storyboard实现cell的动态高度
- Android线程和handler
- 21_Android中常见对话框,光传感器,通过重力感应器编写出指南针应用,帧动画,通过Jav代码的方式编写补间动画,通过XML的方式编写补间动画
- iOS数组和字符串的转化
- Android使用JNI实现Java与C之间传递数据
- Volley从零创建一个简单的文字传输
- CocosDeshion's android.mk 文件的理解
- Swift苹果官方在线文档地址
- [Android]模拟器无法启动:Waiting for HOME ('android.process.acore') to be launched...
- Android 关于shape和selector和layer-list(UI 设计)
- [iOS学习]怎么用返回键设置自定义的图片