Leetcode--Plus One

Source: Internet
Author: User

Question:

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

The digits is stored such, the most significant digit was at the head of the list.

Analysis:

A non-negative number is represented by an array, and then the number is added one.

This topic mainly needs to consider special cases: the numbers are all 9; some of the numbers are 9; the general situation. So take all the circumstances into account and OK.

Answer:

 Public classSolution { Public int[] PlusOne (int[] digits) {        if(Digits = =NULL)            return NULL; if(digits[digits.length-1]! = 9) {Digits[digits.length-1] + +; returndigits; }        BooleanFlag =true;  for(inti=0; i<digits.length; i++) {            if(Digits[i]! = 9) {flag=false;  Break; }        }        if(Flag = =true) {//9 of all digits            int[] res =New int[Digits.length + 1]; res[0] = 1; returnRes; }        Else{//the last one is 9             for(intI=digits.length-1; i>=0; i--) {                if(Digits[i] = = 9) Digits[i]= 0; Else{Digits[i]++; returndigits; }            }        }        returndigits; }    }

Leetcode--Plus One

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.