add-binary(二进制相加)

https://www.nowcoder.com/practice/c8c9f42c19194aa88781efefef4df44b?tpId=46&tqId=29113&tPage=5&rp=5&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking

题目不难, 就是模拟竖式运算,

此做题记录提醒自己写单字符不要不小心加空格,比如字符0 写成 '0 '

虽然在0后面加了空格语法不会报错。。找了半天的bug。。

class Solution {
public:
    string addBinary(string a, string b) {
        int lenA = a.length();
		int lenB = b.length();
		if(lenA == 0 && lenB == 0)
			return "";
		if(lenA == 0)
			return b;
		if(lenB == 0)
			return a;

		int len = max(lenA, lenB);
		//拼接字符串统一长度
		for(int i = 0; i < (len - lenA); i++){
			a = "0" + a;
		}
		for(int j = 0; j < (len - lenB); j++){//同上
			b = "0" + b;

		}
		
		int carry = 0;
		string c = "";
		//模拟竖式相加
		for(int i = len- 1; i >= 0; i--){
			
			int temp = ( a[i] - '0' + b[i] - '0' + carry);//当前为相加和
			c = char((temp % 2) + '0') + c;//拼接
			carry = temp / 2;//得到进位

		
		}
		
		while(carry){//进位弄到结果串c
			c = (char) ( carry % 2 + '0' ) + c;
			carry /=2;
		}
		return c;
    }
};

 

上一篇:LeetCode 2.两数相加


下一篇:67.二进制求和