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
列出两种稍有不同的解法,两者速度伯仲间
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
var cur = n+'';
var path = [n];
while(true){
var tmp = 0;
for(var i = 0,l=cur.length;i<l;i++){
tmp += (cur.charCodeAt(i)-48)*(cur.charCodeAt(i)-48);
}
if(tmp ==1){
return true;
}
for(var j = 0,ll = path.length;j<ll;j++){
if(tmp == path[j]){
return false;
}
}
path.push(tmp);
cur = tmp+'';
}
};
148ms
缺点:每次循环外层都要在字符串和数字之间转换一次,
优点:然转化成字符串以后可以比较轻松的取到数字的长度,后一种方法册需要循环去探测
从字符转数字时直接取编码优于直接字符转数字
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
var cur = n;
var path = [n];
var tmp = 0;
while(true){
<span style="white-space:pre"> </span>tmp = 0;
<span style="white-space:pre"> </span>var y;
<span style="white-space:pre"> </span>while(cur){
<span style="white-space:pre"> </span>y = cur%10;
<span style="white-space:pre"> </span>cur = Math.floor(cur/10);
<span style="white-space:pre"> </span>tmp += y*y;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>if(tmp ==1){
<span style="white-space:pre"> </span>return true;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>for(var i = 0,l = path.length;i<l;i++){
<span style="white-space:pre"> </span>if(tmp == path[i]){
<span style="white-space:pre"> </span>return false;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>path.push(tmp);
<span style="white-space:pre"> </span>cur = tmp;
}
};
156ms
本来以为纯数字的运算会稍微快一点,但实际上没有。
优点:不需要在字符串和数字间进行转换
缺点:可能用除10去探测数字本身的大小其实在这种情况下效率也并不高
每次除法都需要向下取整