Add Binary(C++)

解題思路:

(1)從字符串的末端開始相加

(2)設置進位,判斷和的情況

class Solution {
public:
    /**
     * @param a: a number
     * @param b: a number
     * @return: the result
     */
    string addBinary(string &a, string &b) {
        // write your code here
        int i = a.length()-1,j = b.length()-1;
        int c = 0,sum = 0;
        string str = "";
        while(i>=0 && j>=0) {
            sum = (a[i]-'0')+(b[j]-'0')+c;
            switch(sum){
                case 0:str='0'+str;break;
                case 1:str='1'+str;c=0;break;
                case 2:str='0'+str;c=1;break;
                case 3:str='1'+str;c=1;break;
                default:break;
            }
            i--,j--;
        }
        while(i>=0) {
            sum = (a[i]-'0')+c;
            switch(sum){
                case 0:str='0'+str;break;
                case 1:str='1'+str;c=0;break;
                case 2:str='0'+str;c=1;break;
                default:break;
            }
            i--;
        }
        
         while(j>=0) {
            sum = (b[j]-'0')+c;
            switch(sum){
                case 0:str='0'+str;break;
                case 1:str='1'+str;c=0;break;
                case 2:str='0'+str;c=1;break;
                default:break;
            }
            j--;
        }
        if (c==1) return '1'+str;
        else return str;
        
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章