美文网首页
66. Plus One( JavaScript )

66. Plus One( JavaScript )

作者: f1a94e9a1ea7 | 来源:发表于2018-11-27 20:07 被阅读8次

    给一个整数数组,返回比原来数组大1的数组。

    Example 1:
    • Input: [1,2,3]
    • Output: [1,2,4]
    Example 2:
    • Input: [4,3,2,9]
    • Output: [4,3,3,0]

    解析:

    • 从末尾开始循环
      • 如果这个数不等于 9 ,就直接 + 1 返回
      • 如果等于 9,就把他等于 0,进入到下一轮循环

    (The following English translation may not be right -.-)

    analyze:

    • loop the array from end to start
      • if array[i] not equal 9, array[1] + 1, then return the array
      • else, set the array[i]'s value equals 0, then continue the loop
    var plusOne = function(digits) {
        for(let i = digits.length; i >= 0; i--){
            let num = digits[i-1]
            if(num != 9){
                digits[i-1] = num + 1
                break    
            }else {
                digits[i-1] = 0
                if(i == 1 ){
                    if(digits.length == 1) {
                        digits = [1,0]
                        break
                    }
                    digits.unshift(1)
                }
                
            }
        }
        return digits          
    };
    

    相关文章

      网友评论

          本文标题:66. Plus One( JavaScript )

          本文链接:https://www.haomeiwen.com/subject/kjpnqqtx.html