LeetCode 67.二进制求和

LeetCode 67. 二进制求和

我的思路

先把俩补成一样长的,然后考虑当前位和进位


class Solution {
public:
	string getCompensate(int val) {
		string result = "";
		while (val--) {
			result += '0';
		}
		return result;
	}
	int chartoInt(char a) {
		if (a == '1')    return 1;
		return 0;
	}
	char inttoChar(int a) {
		if (a == 1)	return '1';
		return '0';
	}
	string addBinary(string a, string b) {
		//!null
		int tail_a = a.size() - 1, tail_b = b.size() - 1;

		string compensate = "";
		if (tail_a > tail_b) {
			compensate = getCompensate(tail_a - tail_b);
			b.insert(0, compensate);
		}else if (tail_a < tail_b) {
			compensate = getCompensate(tail_b - tail_a);
			a.insert(0, compensate);
		}
		else;

		int tail = (tail_a > tail_b) ? tail_a : tail_b;

		int flag = 0, temp_result = 0;
		while (tail >= 0) {
			temp_result = chartoInt(a[tail]) + chartoInt(b[tail]) + flag;
			if (temp_result == 2) {
				flag = 1;
				a[tail] = '0';
            }else if(temp_result == 3){
                flag = 1;
                a[tail] = '1';
            }else{
				flag = 0;
				a[tail] = inttoChar(temp_result);
			}
			--tail;
		}
		if (flag == 1)   a.insert(0, "1");
		return a;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值