题目:

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. Exploit搭建

    1,三连下小水管真是慢.去洗澡先. 2,环境变量Path里添加Python安装目录.直接cd到git下来的目录运行sqlmap.py 更新sqlmap,sqlmap.py –update 或 git ...

  2. Android 源码VecotorDrawable

    1 R.styleable.VectorDrawable_viewportWidth 该资源的名字并非VectorDrawable_viewportWidth 而是 attrs.xml 下的声明 &l ...

  3. JS传参出现乱码(转载)

    问题说明:在进行网站开发时,将表单的提交功能交给JS来传递,但是在传递中文的过程中出现类似于繁体字的乱码. 解决方案:为了解决这个问题,首先从底层的C#代码审查,重新设置页面传值进行模拟,但是几经测试 ...

  4. iOS编程——经过UUID和KeyChain来代替Mac地址实现iOS设备的唯一标示(OC版)

    iOS编程——通过UUID和KeyChain来代替Mac地址实现iOS设备的唯一标示(OC版) 很多的应用都需要用到手机的唯一标示,而且要求这个唯一标示不能因为应用app的卸载或者改变而变化. 在iO ...

  5. Android使用百度地图API实现GPS步行轨迹

    百度地图Android SDK下载:http://developer.baidu.com/map/sdkandev-download.htm 下面是效果: 采样点取得太频繁所以看起来像是一个个点... ...

  6. HTMLEncode httpencode UTF8Encode

    1.引用单元:  httpApp; 2. 对于 http Post的提交内容,应该是:   HttpEncode(Utf8Encode(StrValue));   不然与web方式的 Url_enco ...

  7. DOM基础总结

    一.简介 1.什么是DOM 文档对象模型(Document Object Model,DOM)是一种用于HTML和XML文档的编程接口.它给文档提供了一种结构化的表示方法,可以改变文档的内容和呈现方式 ...

  8. 【Python笔记】异常处理

    1 什么是异常 异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行.一般情况下,在Python无法正常处理程序时就会发生一个异常.异常是Python对象,表示一个错误. 当Pytho ...

  9. FatMouse

      时间限制:1 秒 内存限制:128 兆 特殊判题:否 提交:1431 解决:641 题目描述: FatMouse prepared M pounds of cat food, ready to t ...

  10. Java中的break与continue区别

    break跳出当前循环执行循环下面的程序, 如果break出现在嵌套循环的内层循环, 则break语句只会跳出当前层的循环; 当程序执行到continue时时, 则跳过本次循环程序重新回到循环开始继续 ...