leetcode 66 Plus One

题目详情

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
题目的意思是,给你一个用int数组表示的一个非负整数。你须要返回这个整数加1后,所对应的int数组。

解法一

  • 主要须要关注的点就在于,当末尾数字为9的时候的进位状况。
  • 若是不须要进位了,则表明循环能够结束了。此时直接返回输入的digits数组
  • 若是数组的全部元素都为9,则须要在最前面补一位1,咱们应该意识到剩下的位都为0,不须要经过循环赋值,只须要把数组的第一位赋值为1就能够,剩下的元素天然为0
public int[] plusOne(int[] digits){
        int carry = 1;    
        
        for(int i=digits.length-1;i>=0;i--){
            if(digits[i] + carry == 10){
                digits[i] = 0;
                carry = 1;
            }else{
                digits[i] = digits[i] + carry; 
                return digits;
            }            
            
        }
        
        int[] res = new int[digits.length+1];
        res[0] = 1;
        return res;
        
    }
相关文章
相关标签/搜索