首页 > 代码库 > 每日算法之四十八:Plus One (数组表示的十进制加一进位)以及求Sqrt(x)

每日算法之四十八:Plus One (数组表示的十进制加一进位)以及求Sqrt(x)

给定数组表示的十进制数,加一操作。结果依然用十进制的数组表示。这里主要注意最高位(digit[0])依然有进位,即溢出的情况。

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;     // 误差
        int low = 0;
        int high = x;
         
        while(low <= high){
            // 注意越界!所以用double来存
            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;
            }
        }
         
        // 当找不到时候,这是low,high指针已经交叉,取较小的,即high
        return high;
    }
};




每日算法之四十八:Plus One (数组表示的十进制加一进位)以及求Sqrt(x)