Leetcode 202 Happy Number
2015-07-01 14:37
435 查看
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,必定存在某次情况使得得到的值等于之前生成过的值。
*js的Array没有内置contains/include函数,需要自己添加。
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,必定存在某次情况使得得到的值等于之前生成过的值。
*js的Array没有内置contains/include函数,需要自己添加。
Array.prototype.contains = function (x) { for (var i in this) if (this[i] == x) return true return false } var isHappy = function(n) { var temp = [] var s = n.toString() while (true){ var sum = 0 for (var i=0;i<s.length;i++) sum += s[i]*s[i] if(sum == 1) return true else if (temp.contains(sum)) return false temp.push(sum) s = sum.toString() } }
相关文章推荐
- Android Studio library发布JCenter编码错误_编码GBK的不可映射字符
- IOS 给类目添加属性
- Swift开发学习(一):初始篇
- android 软键盘隐藏
- Android 4.4 eng版本 红框问题
- Slideout.js触摸滑出式 Web App 导航菜单调用方法
- 崩溃问题收集1----Illegal property type, c for appearance setter, _installAppearanceSwizzleForSetter
- Swift数据类型(基础篇)
- 对数组进行各种操作
- android中onNewIntent的简单说明
- Android ADB server didn't ACK * failed to start daemon * 简单有效的解决方案
- Unity3d《Shader篇》描边
- Android的AlertDialog详解(转载)
- android 项目R.java文件缺失导致编译错误
- AppDelegate中几个惯用的回调调用时机
- Android Percent Layout 安卓百分比布局
- 接口和扩展
- 怎么样android app正在使用STL库
- Android中的数据格式化
- Android---- 获取当前应用的版本号和当前android系统的版本号