Add Binary

it2025-06-17  7

问题描写叙述:Given two binary strings, return their sum (also a binary string).

For example, a = “11” b = “1” Return “100”. 解决方式:

class Solution { public: string addBinary(string a, string b) { int aLen = a.size(); int bLen = b.size(); int i = aLen-1; int j = bLen-1; int c = 0; int num; string result; while(i>=0&&j>=0) { num = a[i]-'0'+b[j]-'0'+c; c = num/2; num = num%2; result = char(num+'0')+result;//此处的想法比較关键,用一个字符串的加法从后向前加入字符。 i--; j--; } while(i>=0) { num = char(a[i]-'0')+c; c = num/2; num=num%2; result = char(num+'0')+result; i--; } while(j>=0) { num =b[j]-'0'+c; c = num/2; num=num%2; result = char(num+'0')+result; j--; } if(c>0) { result = '1'+result; } return result; } };

转载于:https://www.cnblogs.com/bhlsheji/p/5155605.html

最新回复(0)