Leetcose-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.

Problem:

The problem is simple: a non-negative integer is given, which is represented by an array to change the non-negative integer. For example, 321 is used to give a three-digit array [3] [2] [1], and add one to the array, returns an array of results.

Analysis:

Consider two special cases, for example, [1] [9], [9] [9] [9] [9]. The former directly enters one space, and the latter creates an array with one more space to save the result.

Public class solution {public int [] plusone (INT [] digits) {int length = digits. length; int I = 0; If (digits [length-1]! = 9) if the last digit is not 9, add 1 digits [length-1] + = 1; else {for (I = length-1; digits [I] = 9; I --) {otherwise, find the if (I = 0) where the first digit is not 9 from the last forward loop) {if I = 0, it indicates that the given array is 9. In the second case, int [] result = new int [Length + 1]; Result [0] = 1; for (Int J = 1; j <= length; j ++) result [J] = 0; return result;} else {otherwise I! If it is set to 0, it is normal to carry digits [I] = 0;} digits [I] + = 1;} return digits ;}}

 

Leetcose-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.