Leetcode 67 —— Add Binary

Total Accepted: 78879 Total Submissions: 291470 Difficulty: Easy

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

Subscribe to see which companies asked this question

Hide Tags
 Math String

題意:

計算字符串的加法 返回結果字符串。


思路比較簡單,注意字符串拼接以及進位的判斷。


代碼(已AC 2016-03-24)~

string addBinary(string a, string b) {
	if (a.empty() || b.empty())
	{
		return (a.empty()) ? b : a;
	}

	int inc = 0, posA = a.length() - 1, posB = b.length() - 1, sum = 0;
	string res("");
	while (posA >= 0 && posB >= 0)
	{
		sum = (a[posA] - '0') + (b[posB] - '0') + inc;
		inc = sum / 2;

		res = (char)(sum % 2 + '0') + res;

		posA--, posB--;
	}

	while (posA > -1)
	{
		sum = (a[posA] - '0') + inc;
		inc = sum / 2;

		res = (char)(sum % 2 + '0') + res;
		posA--;
	}

	while (posB > -1)
	{
		sum = (a[posB] - '0') + inc;
		inc = sum / 2;

		res = (char)(sum % 2 + '0') + res;
		posB--;
	}

	if (inc)
		res = (char)(inc + '0') + res;

	return res;
}


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