leetCode : plus one

来源:互联网 发布:java 读取ftp文件流 编辑:程序博客网 时间:2024/05/23 14:56

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.


题意:

给你一个用数组表示的数,求加一之后的结果,结果还是用数组表示。

解题思路:

从数组的最后一位开始加1,需要考虑进位,如果到[0]位之后仍然有进位存在,首位插入一。


/** * @param {number[]} digits * @return {number[]} */var plusOne = function(digits) {    var len = digits.length-1;    while(digits[len] === 9)         digits[len--] = 0; //把当前len所在位的值置为0之后减一检测前一位是否为9;    if(len < 0)         digits.splice(0,0,1);    else         digits[len]++;    return digits;};


0 0