LeetCode -- Happy Number
2015-10-14 00:05
232 查看
题目描述:
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则返回true,否则使用哈希来存已经计算过的数字。如果已经在哈希中存在,返回false。
实现代码:
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则返回true,否则使用哈希来存已经计算过的数字。如果已经在哈希中存在,返回false。
实现代码:
public class Solution { public bool IsHappy(int n) { var digs = n.ToString(); var hash = new Dictionary<int, bool>(); while(true){ int r = 0; for(var i = 0;i < digs.Length; i++){ var x = int.Parse(digs[i].ToString()); r += x * x; } if(r == 1){ return true; } if(!hash.ContainsKey(r)){ hash.Add(r, true); digs = r.ToString(); } else{ return false; } } } }
相关文章推荐
- 浅谈angular.js中实现双向绑定的方法$watch $digest $apply
- 利用 CMake 和 NDK 交叉编译 Android 下的可执行程序
- app手机应用市场免费资源分享-APP开发、APP定制、APP外包
- FlipViewPager 对item实现左右对折滑动翻页效果《IT蓝豹》
- [Swift]UIKit学习之UITextField的用法
- javascript 中 call apply 方法的区别
- IOS(Simulator)模拟器切换横竖屏的快捷键
- Android事件分发
- MindMapper中怎样插入关联性
- Android学习(十)AudioFlinger(2)
- Android客户端向服务器端传值——登录实现
- AppleWatch开发入门二——界面布局
- Android 开发中的日常积累
- iOS 苹果官方Demo合集
- 安卓高级计算器完整版
- Android JNI使用总结(二)
- Android学习实践:11.进度条ProgressBar
- android第一课:android开发环境搭建
- Android学习基本索引(三)——记录,没事自己看
- 改变webView中请求的JS数据