码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode练习:258. Add Digits & 415. Add Strings

时间:2017-10-24 20:53:00      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:add   color   contains   recursion   ber   公式   you   turn   uil   

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

var addDigits = function(num) {
    var res = num;

    while(res >= 10){
        num = res;
        res = 0;
        while(num>0){
            res = res + num % 10;
            num = parseInt(num / 10);
        }
    }
    
    return res;
};

题目后续:写成不用循环的方法,查了一下百度发现还有数学公式来着,就可以不用循环了0_0。

公式是(num-1)%9+1

 

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
var addStrings = function(num1, num2) {
    if(num1.length < num2.length) {
        var _swap = num1;
        num1 = num2;
        num2 = _swap;
    }
    
    var i = num1.length -1;
    var j = num2.length -1;
    var res = [];
    var cur=0,cin=0;
    
    while(j>=0){
        cur = (cin + parseInt(num1[i]) + parseInt(num2[j])) % 10;
        cin = parseInt((cin + parseInt(num1[i]) + parseInt(num2[j])) / 10);
        res.unshift(cur);
        j--;
        i--;
    }
    
    while(i>=0){
        if(cin>0){
             cur = (cin + parseInt(num1[i])) % 10;
             cin = parseInt( (cin + parseInt(num1[i]) ) / 10);  
             res.unshift(cur);
        } else {
            res.unshift(parseInt(num1[i]));
        }
        i--;
    }
    
    if(cin>=1){
        res.unshift("1");
    }
    
    return res.join(‘‘);
};

 

leetcode练习:258. Add Digits & 415. Add Strings

标签:add   color   contains   recursion   ber   公式   you   turn   uil   

原文地址:http://www.cnblogs.com/rimochiko/p/7725253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!