码疯窝

LeetCode 每日一题 — Add Digits

2015/09/16 15:32:40    分类: 技术随笔    1人评论 次浏览

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.

PS: js就是那么的高能. 无比的简洁的代码.

JavaScript:

var addDigits = function(num) {
    var rst = 0;
    Array.prototype.forEach.call(num + '', function (v) { rst += +v; });
    return rst < 10 ? rst : addDigits(rst);
};
继续查看有关 技术随笔的文章

1个访客评论

  1. 123

    路过。。。www.baidu.com

    qweqwe Reply