Happy Number
2015-08-16 10:59
363 查看
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
题目的关键是一直不等于1循环什么时候终止?终止的条件是number在以前的计算
中出现过,这样就没有再计算的必要了。
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
题目的关键是一直不等于1循环什么时候终止?终止的条件是number在以前的计算
中出现过,这样就没有再计算的必要了。
public class Solution { public boolean isHappy(int n) { HashSet<Integer> set=new HashSet<Integer>(); while(n!=1){ if(set.contains(n)) return false; set.add(n); n=getNextNumber(n); } return true; } private int getNextNumber(int n){ int result=0; while(n!=0){ result+=(n%10)*(n%10); n/=10; } return result; } }
相关文章推荐
- android环境配置
- 中文 iOS/Mac 开发博客列表
- Android onPause 和onSaveInstanceState
- cocos2dx --- button点击放大中心
- 使用FDTemplateLayout框架打造个性App
- android圆形旋转菜单,而对于移动转换功能支持
- 严重: Error configuring application listener of class org.springframework.web.context.ContextLoaderLis
- 窥探Swift之新添数据类型元组与可选值
- Objective-C葵花宝典第一重(内功篇)--类与对象
- swtich/if...else的替代语句
- Swift开发过程中常用到的一些使用技巧和注意的地方
- ADT导出Android工程到Androidstudio
- android跨进程通讯一:android中跨进程通讯的4种方式
- Android studio百度地图(一)
- iOS应用中增加emoji表情输入功能
- Swiftl优秀的特性
- IOS开发之----详解在IOS后台执行
- 关于掌纹识别的android版本开发(实例调用JNI)
- IOS 开发:绘制像素到屏幕
- Android Studio系列教程三--快捷键