[leetcode] 202. Happy Number
2016-01-03 22:18
417 查看
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
Credits:
Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.
[Solution]
不是happy number的话,结果会出现循环,用set记录所有结果,出现重复则为false
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
Credits:
Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.
[Solution]
不是happy number的话,结果会出现循环,用set记录所有结果,出现重复则为false
bool isHappy(int n) { set<int> table; table.insert(n); while (1) { int k = 0; while (n) { k += (n % 10) * (n % 10); n /= 10; } if (k == 1) return true; if (table.find(k) != table.end()) return false; n = k; table.insert(n); } }
相关文章推荐
- Android之横竖屏切换内容丢失问题解决方法
- Android中Sharedpreferences牵涉到跨进程时不能实时读取的问题
- Swift2.1-自动引用计数
- android service
- 【Android进阶】如何写一个很屌的动画(2)---动画的好帮手们
- Android 自定义seekbar【仿微信联系人】
- App研发录 架构设计 Crash分析和App竞品技术分析
- iOS开发使用tableView从服务器加载图片时的卡顿现象解决方案
- Android Activity和intent
- android 修改ramdisk.img
- iOS多线程入门
- eatwhatApp开发实战(七)
- ios:协议、闭包、通知三种传值方式
- APP 自动化框架设计思路分享
- Android Studio快捷键每日一练(5)
- 什么是aidl?Android AIDL详解
- iOS中多线程的简介
- Android序列化——Serializable与Parcelable
- 移动端页面调试工具——UC浏览器开发者版
- js'中的apply和call和bind的用法