Add Digits

来源:互联网 发布:淘宝苹果组装机 编辑:程序博客网 时间:2024/04/30 14:05

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 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

var addDigits = function(num) {   var str = num.toString(), res = 0, tmp1, tmp2;    for(var i = 0; i < str.length; i++){        res = parseInt(str[i]) + res;       if(res >= 10){            tmp1 = parseInt(res / 10);            tmp2 = res % 10;            res = tmp1 + tmp2;         }    }    return res;};
0 0
原创粉丝点击