美文网首页leetcode --- js版本程序员
leetcode-Easy-第13期-数组-Plus One

leetcode-Easy-第13期-数组-Plus One

作者: 石头说钱 | 来源:发表于2019-03-09 09:24 被阅读4次

题目:

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.

题目看了好几遍才明白到底要问什么...就是给你一个:非空数组,元素都是正数的数组,然后将数组里面的元素看成一个整数,比如[1,2,3,4]数组整数就是1234,然后将这个整数加上1后得到的结果是多少,还是用数组表示

  • 例1:
数组:[1,2,3,4]
1234 + 1   = 1235
结果用数组表示:[1,2,3,5]
  • 例2:
数组:[1,2,9,9]
1239 + 1   = 1300
结果用数组表示:[1,3,3,0]
  • 例3:
数组:[9,9,9,9]
1239 + 1   = 10000
结果用数组表示:[1,0,0,0,0]
  • 思路
三种情况:
1 最后一位小于9,直接加1返回2
2 不是所有数字都为9,所以遍历到的那一位加1大于10,向前进1,当前位变0
3 所有数字都是9,全部变为0,然后最左边添加一个元素1

  • 解法
var plusOne = function(arr) {
   const len  = digits.length - 1;
    for(let i = len; i >= 0; i--){
    // 如果当前遍历到的元素小于9那么加上1以后,就结束返回结果即可
       if(digits[i] < 9){
          digits[i] += 1;
          return digits; //当前
        }
    // 第当前位加1大于10,那么当前位变为0,下一位进1
      digits[i] = 0
    }
 //上面没有return,执行到这里表明所有元素都为9
//所以给数组首位添加一个1
    digits.unshift(1);
    return digits;
};

相关文章

网友评论

    本文标题:leetcode-Easy-第13期-数组-Plus One

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