Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

66 大数加1 #14

Closed
sailei1 opened this issue May 16, 2019 · 0 comments
Closed

66 大数加1 #14

sailei1 opened this issue May 16, 2019 · 0 comments

Comments

@sailei1
Copy link
Owner

sailei1 commented May 16, 2019

给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。

最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。

你可以假设除了整数 0 之外,这个整数不会以零开头。

示例 1:

输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
示例 2:

输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。

解法:
字符串转number 有溢出的问题,所以放弃。

从数组最后一位判断是否需要进位 比如49+1=50 9+1=0 再4+1;
依次类推 999 +1 =1000

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
      let f=true;
     let ls=digits.length;
     for(let i=ls-1;i>=0;i--){
         if(digits[i]+1>9){  //大于9 数位循环+1;
             digits[i]=0;
         }else{
             digits[i]+=1;   //+1后 小于10 停止  
             f=false; // 进位标记
             break;
         }
     }
     if(f){
        digits.unshift(1);  // 999 情况 进1 
    }
     console.log(digits);
    return digits;
    
};

@sailei1 sailei1 closed this as completed May 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant