题目:

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的更多相关文章

  1. Leetcode 202 Happy Number 弗洛伊德判环解循环

    今天先谈下弗洛伊德判环,弗洛伊德判环原来是在一个圈内有两人跑步,同时起跑,一人的速度是另一人的两倍,则那个人能在下一圈追上另一个人,弗洛伊德判环能解数字会循环出现的题,比如说判断一个链表是不是循环链表 ...

  2. LeetCode 202 Happy Number

    Problem: Write an algorithm to determine if a number is "happy". A happy number is a numbe ...

  3. 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' ...

  4. Java for LeetCode 202 Happy Number

    Write an algorithm to determine if a number is "happy". A happy number is a number defined ...

  5. (easy)LeetCode 202.Happy Number

    Write an algorithm to determine if a number is "happy". A happy number is a number defined ...

  6. 【LeetCode】202 - Happy Number

    Write an algorithm to determine if a number is "happy". A happy number is a number defined ...

  7. Java [Leetcode 202]Happy Number

    题目描述: Write an algorithm to determine if a number is "happy". A happy number is a number d ...

  8. LeetCode OJ 202. Happy Number

    Write an algorithm to determine if a number is "happy". A happy number is a number defined ...

  9. 40. leetcode 202. Happy Number

    Write an algorithm to determine if a number is "happy". A happy number is a number defined ...

随机推荐

  1. Redis配置中文翻译,3.2.1版

    大部分常见设置都翻译了,还有一些是从网上复制的(懒) # Redis configuration file example. ## Redis配置文件示例 # # Note that in order ...

  2. 选择问题(选出第i个最小元素)

    通过分治法解决的分析(还有其他方法解决选择问题如使用 堆) 1 同快速排序一样,对输入的数组进行递归分解 不同的是:快速排序会递归处理分解的两边,而选择问题只处理需要的一边 2 选择问题的期望时间代价 ...

  3. [java学习笔记]java语言核心----面向对象之static关键字

    static关键字用处 用于修饰成员变量和成员函数 被修饰后的成员具有以下特点: 随着类的加载而加载 优先于对象存在 被所有对象所共享 可以直接被类名调用 使用注意 静态方法只能访问静态成员:非静态方 ...

  4. [转]mysql-5.6.17-win32免安装版配置

    1. 下载mysql-5.6.17-win32:官网下载地址百度 2. 解压到自定义目录,我这里演示的是D:\wamp\mysql\ 3. 复制根目录下的my-default.ini,改名为my.in ...

  5. ▲▲▲▲▲▲▲▲▲▲▲yum源的配置(本地和ftp)▲▲▲▲▲▲▲▲▲▲▲▲▲v

    ★★★★★★★★★★★★★★★本机yum源★★★★★★★★★★★★★★★★ 1. 首先把DVD里的OS镜像mount处理,如果插入光驱自动mount的话,一般在/media下面,比如RHEL_6.3 ...

  6. js 中的正则表达式

    一:正则表达式 定义:记录文本规则的代码 作用:表单验证,爬虫技术,可以对目标的内容进行替换. 二:正则表达式的组成 1:普通字符组成正则 浏览器的输出 2:定义字符集组成正则 3:特殊字符集组成正则 ...

  7. winfrom LED时钟

    public sealed class Clock : PictureBox { public Clock() { SetStyle(ControlStyles.AllPaintingInWmPain ...

  8. Asp.net 引用css/js资源文件

    注意Page.ResolveUrl之前的双引号,不是单引号 <script type="text/javascript" src="<%= Page.Reso ...

  9. java 中的this关键字的几种用法

    转自:http://blog.csdn.net/anmei2010/article/details/4091227 1.     当成员变量和局部变量重名时,在方法中使用this时,表示的是该方法所在 ...

  10. max_size, capacity and size 的区别

    The max_size() function returns the maximum number of elements that the container can hold. The max_ ...