Forty-eight daily algorithms: plus one (an array of decimal digits plus one digit) and SQRT (X)

Source: Internet
Author: User

Given the decimal number represented by an array, add one. The result is still represented in a decimal array. Here, we mainly note that the highest bit (digit [0]) still has an incoming bit, that is, overflow.

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.


<span style="font-size:18px;">class Solution {public:    vector<int> plusOne(vector<int> &digits) {        int len = digits.size();        if(len == 0)            return digits;        int carry = 1;int temp = 0;        for(int i = len-1; i>=0; i--)        {            temp = (digits[i] + carry)/10;            digits[i] = (digits[i] + carry)%10;            carry = temp;        }        if(carry > 0)        {            vector<int> ret(len+1, 0);            ret[0] = 1;            return ret;        }        else            return digits;    }};</span>


SQRT (x ):

Class solution {public: int SQRT (int x) {double diff = 0.01; // error int low = 0; int high = x; while (low <= high) {// pay attention to cross-border! So double mid = low + (high-low)/2; If (ABS (mid * mid-x) <= diff) {return (INT) Mid ;} else if (x> mid * Mid + diff) {LOW = (INT) Mid + 1;} else if (x <mid * mid-diff) {high = (INT) mid-1 ;}/// when it cannot be found, this is low, the high pointer has been crossed, take a smaller value, that is, high return high ;}};




Forty-eight daily algorithms: plus one (an array of decimal digits plus one digit) and SQRT (X)

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.