Leetcode notes: Plus One

Source: Internet
Author: User

Leetcode notes: Plus One

I. Description

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

Ii. Question Analysis

A high-precision computing question, from low to high for calculation, while considering the carry problem, if the highest bit calculation result has a carry, you need to add a bit before the highest bit. The time complexity is O (n) and the space complexity is O (1 ).

This question should be a simplified version, because it is only required to add 1 to a number. If any bitwise operation has no carry-in, the carry-in process is not required for a higher level, and the result can be output directly.

Iii. instance code

# Include
  
   
# Include
   
    
Using namespace std; class Solution {public: void plusOne (vector
    
     
& Digits) {int carry = 1; const int digitsSize = digits. size (); for (int I = digitsSize-1; I> = 0; I --) {digits [I] + = carry; if (digits [I] <10) {carry = 0; break;} carry = digits [I]/10; digits [I] % = 10;} if (carry! = 0) // if the highest bit operation still has a forward digit, you need to add a union of 1 digits. insert (digits. begin (), carry );}};
    
   
  

Two running results:

Iv. Summary

It is also a problem involving bit operations. There are many solutions, and we should consider what to do when the plus value is different.

 

Related Article

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.