Leetcode plus one

Source: Internet
Author: User

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.

 

Input a number, which is expressed as an array. The array is the number from high to low. Then the number is + 1; the returned result is.

The solution is case-based discussion. If there is no carry-in, it will be output directly. If there is an incoming bit and the array overflows, a new array will be returned.

 1 public class Solution { 2     public int[] plusOne(int[] digits) { 3             int oneplus=0; 4             for (int i = digits.length-1; i >=0; i--) { 5                 if (digits[i]<9) { 6                     digits[i]++; 7                     oneplus=0; 8                     break; 9                 }else {10                     oneplus=1;11                     digits[i]=0;12                 }13             }14             15             if (oneplus == 1) {16                 int[] res = new int[digits.length+1];17                 res[0]=1;18                 for (int i = 1; i < res.length; i++) {19                     res[i]=digits[i-1];20                 }21                 return res;22             }23             24             return digits;25     }26 }

 

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.