[LeetCode 67,69][簡單]二進制求和(模擬)/x的平方根(牛頓法)

67.二進制求和
題目鏈接

class Solution {
public:
    void upd(string &c,int add,int &op){
        c += to_string((add + op) & 1);
        op = (add + op) >> 1;
    }
    string addBinary(string a, string b) {
        int al=a.size(),bl=b.size();
        string c="";
        int op=0;
        while(al&&bl)upd(c,a[--al]+b[--bl]-2*'0',op);
        while(al)upd(c, a[--al]-'0', op);
        while(bl)upd(c, b[--bl]-'0', op);
        while(op)upd(c, 0, op);
        reverse(c.begin(),c.end());
        return c;
    }
};

69.x的平方根
題目鏈接
可以複習牛頓法

class Solution {
public:
    int mySqrt(int x) {
        if(x==0)return 0;
        double ans = 1.0;
        while(fabs(ans * ans - x )>0.9){//這個0.5可以考慮牛頓法求根方法的幾何定義來理解,只要是個小於1的數就可以
            ans = (ans * ans + x)/(2.0 * ans);
        }
        return (int) ans;
    }
};

真想用庫函數曲線救國可以

class Solution {
public:
    int mySqrt(int x) {
       return (int)pow(2,log2(x)/2);
    }
};
發佈了104 篇原創文章 · 獲贊 13 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章