[leetcode][javascript]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


列出两种稍有不同的解法,两者速度伯仲间

/**
 * @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去探测数字本身的大小其实在这种情况下效率也并不高
   每次除法都需要向下取整


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值