202. Happy Number
题目:
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
链接: http://leetcode.com/problemset/algorithms/
题解:
判断一个数字是否为Happy Number。这道题跟求无限循环小数很像,最好维护一个HashSet,假如遇见重复,则返回false。否则替换n为digits square root sum,当n == 1时循环结束返回true。
Time Complexity - O(n), Space Complexity - O(n)。
public class Solution {
public boolean isHappy(int n) {
if(n <= 0)
return false;
Set<Integer> set = new HashSet<>(); while(n != 1) {
if(set.contains(n))
return false;
else {
set.add(n);
n = getSquareSumOfDigits(n);
}
} return true;
} private int getSquareSumOfDigits(int n) {
int res = 0; while(n > 0) {
res += (n % 10) * (n % 10);
n /= 10;
} return res;
}
}
二刷:
就是在i != 1的情况对n进行处理,使用一个Set来保存出现过的数字,假如重复则出现循环,这时候我们return false。否则跳出循环的时候n == 1,我们return true。
Java:
Time Complexity - O(n), Space Complexity - O(n)。 时间复杂度和空间复杂度需要用数学公式来推算。这公式是什么我现在也不知道。
public class Solution {
public boolean isHappy(int n) {
if (n < 1) {
return false;
}
Set<Integer> set = new HashSet<>();
set.add(n);
int newNum = 0;
while (n != 1) {
while (n != 0) {
newNum += (n % 10) * (n % 10);
n /= 10;
}
if (!set.add(newNum)) {
return false;
}
n = newNum;
newNum = 0;
}
return true;
}
}
题外话: 今天试了一下Coursera的Crytography I,感觉难度比较大,需要很好的概率知识。做作业的时候参考了别人在github上写的Python代码,好简洁。自己也要好好练起来。又发现了几个比较优美的算法课件,都是来自Kevin Wayne,要好好看一看。其实至今为止自己收集了很多资料,包括书籍,课件,Source Code, Video等等,但总觉得没准备好,心里没底,也许是因为这leetcode到现在第一遍还没完成吧。说不定真刷到了5遍7遍的,融会贯通了以后,才会安心一点。
三刷:
Java:
public class Solution {
public boolean isHappy(int n) {
if (n < 1) {
return false;
}
Set<Integer> set = new HashSet<>();
set.add(n);
while (n != 1) {
n = getSquareSum(n);
if (!set.add(n)) {
return false;
}
}
return true;
} private int getSquareSum(int num) {
int res = 0;
while (num != 0) {
int remainder = num % 10;
res += remainder * remainder;
num /= 10;
}
return res;
}
}
Update:
public class Solution {
public boolean isHappy(int n) {
if (n < 1) return false;
Set<Integer> set = new HashSet<>();
while (n != 1) {
int num = 0;
while (n != 0) {
num += (n % 10) * (n % 10);
n /= 10;
}
if (!set.add(num)) return false;
n = num;
}
return true;
}
}
更好的解可以把Space Complexity 简化到 O(1),使用 fast / slow pointer进行Cycle Detection的思路,很巧妙。 更奇妙的是运行时间也减少了。
public class Solution {
public boolean isHappy(int n) {
if (n < 1) {
return false;
}
int x = n, y = getDigitSquareSum(n);
while (x != y) {
x = getDigitSquareSum(x);
y = getDigitSquareSum(getDigitSquareSum(y)); }
return x == 1;
} private int getDigitSquareSum(int n) {
int res = 0;
while (n > 0) {
int curDigit = n % 10;
res += curDigit * curDigit;
n /= 10;
}
return res;
}
}
Update:
public class Solution {
public boolean isHappy(int n) {
if (n < 1) return false;
int slow = n, fast = getSquareSum(n);
while (slow != fast) {
slow = getSquareSum(slow);
fast = getSquareSum(getSquareSum(fast));
}
return slow == 1;
} private int getSquareSum(int n) {
int num = 0;
while (n != 0) {
num += (n % 10) * (n % 10);
n /= 10;
}
return num;
}
}
四刷:
class Solution {
Set<Integer> set = new HashSet<>(); public boolean isHappy(int n) {
if (n < 1) return false;
if (set.contains(n)) return n == 1;
else set.add(n);
return isHappy(getSquareSum(n));
} private int getSquareSum(int n) {
int num = 0;
while (n != 0) {
num += (n % 10) * (n % 10);
n /= 10;
}
return num;
}
}
Reference:
https://leetcode.com/discuss/33055/my-solution-in-c-o-1-space-and-no-magic-math-property-involved
https://leetcode.com/discuss/71625/explanation-those-posted-algorithms-mathematically-valid
https://leetcode.com/discuss/33349/o-1-space-java-solution
http://www.cs.princeton.edu/courses/archive/spring13/cos423/lectures.php
http://www.cs.princeton.edu/courses/archive/fall12/cos226/lectures.php
202. Happy Number的更多相关文章
- Leetcode 202 Happy Number 弗洛伊德判环解循环
今天先谈下弗洛伊德判环,弗洛伊德判环原来是在一个圈内有两人跑步,同时起跑,一人的速度是另一人的两倍,则那个人能在下一圈追上另一个人,弗洛伊德判环能解数字会循环出现的题,比如说判断一个链表是不是循环链表 ...
- LeetCode 202 Happy Number
Problem: Write an algorithm to determine if a number is "happy". A happy number is a numbe ...
- leetCode191/201/202/136 -Number of 1 Bits/Bitwise AND of Numbers Range/Happy Number/Single Number
一:Number of 1 Bits 题目: Write a function that takes an unsigned integer and returns the number of '1' ...
- Java for LeetCode 202 Happy Number
Write an algorithm to determine if a number is "happy". A happy number is a number defined ...
- (easy)LeetCode 202.Happy Number
Write an algorithm to determine if a number is "happy". A happy number is a number defined ...
- 【LeetCode】202 - Happy Number
Write an algorithm to determine if a number is "happy". A happy number is a number defined ...
- Java [Leetcode 202]Happy Number
题目描述: Write an algorithm to determine if a number is "happy". A happy number is a number d ...
- LeetCode OJ 202. Happy Number
Write an algorithm to determine if a number is "happy". A happy number is a number defined ...
- 40. leetcode 202. Happy Number
Write an algorithm to determine if a number is "happy". A happy number is a number defined ...
随机推荐
- linux 安装mysql后修改密码出现问题
新安装的mysql 执行命令时候出现错误: 一 错误信息: ERROR 1045 (28000): Access denied for user 'mysql'@'localhost' (using ...
- js 正则实例
1.匹配url参数 var re = /([^&=]+)=?([^&]*)/g while (r = re.exec("aaa1a=aabbbbbbb")) { a ...
- Windows Phone 为指定容器内的元素设置样式
在Windows Phone中设置元素样式有多种 拿TextBlock来说 1.我们可以直接在控件上设置: <TextBlock Text="自身样式设置" Width=&q ...
- CentOs Linux 分区建议
硬盘分区方案 在计算机上安装Linux系统,对硬盘进行分区是一个非常重要的步骤,下面介绍几个分区方案. (1)方案1(桌面)/boot:用来存放与Linux系统启动有关的程序,比如启动引导装载程序等, ...
- 【C#】数据库备份及还原的实现代码【转载】
[转载]http://www.codesky.net/article/200908/128600.html C#数据库备份及还原1.在用户的配置时,我们需要列出当前局域网内所有的数据库服务器,并且要列 ...
- JS基础类型和对象,分别是按值传递还是按引用传递?
在分析这个问题之前,我们需了解什么是按值传递(call by value),什么是按引用传递(call by reference).在计算机科学里,这个部分叫求值策略(Evaluation Strat ...
- Node.js 【使用npm安装一些包失败之笔记】
镜像使用方法(三种办法任意一种都能解决问题,建议使用第三种,将配置写死,下次用的时候配置还在): 1.通过config命令 npm config set registry https://regist ...
- Mvc生命周期深度剖析
客户端发送请求->IIS, UrlRouting模块对比URL, 默认如果该URL能对应到实体文件则退出MVC管道把控制权交还给IIS. 如果RegisterRoutes中的路由规则对比成功默认 ...
- NGUI系列教程八(监听NGUI的事件方法)
NGUI事件的种类很多,比如点击.双击.拖动.滑动等等,他们处理事件的原理几乎万全一样,本文只用按钮来举例. 1.直接监听事件 把下面脚本直接绑定在按钮上,当按钮点击时就可以监听到,这种方法不太好很不 ...
- GIS业务逻辑
三维怎么加载数据文件? OpenFileDialog frm = new OpenFileDialog(); frm.Filter = "文件数据集|*.tile|多时相数据集|*.Temp ...