Leetcode[66]-plus One

Source: Internet
Author: User

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.

Test instructions: Given an array that represents the number of non-negative bits, the number is now added one, and the resulting array is added.

Analysis: Because the length of the array may change after the addition, it is not straightforward to add one directly behind the array. The array can be flipped first, the bits go to the front, and then from the go to add one, and finally determine if the last one added more than ten, the array length plus one, the code is as follows:

Code (c + +):

classSolution { Public: vector<int>PlusOne ( vector<int>& digits) {intn = digits.size (); Reverse (Digits.begin (), Digits.end ());inttemp =0, flag =false; for(inti =0; I<n; i++) {if(i==0) temp =1;intsum = digits[i] + temp; Digits[i] = sum%Ten; temp = sum/Ten;if(i = = n1&& sum >=Ten) flag =true; }if(flag) {Digits.resize (n+1);        Digits[n] = temp; } reverse (Digits.begin (), Digits.end ());returnDigits }};

Leetcode[66]-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.