标签:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
;
思路: 对齐, 计算当前位和进位;
如果位较长,让我想到了先行进位加法器,不过这里的计算不能并行,也无什么效果。
//add Binary class Solution { public: string addBinary(string a, string b) { // Start typing your C/C++ solution below // DO NOT write int main() function string c; int flag=0; int lena = a.size(); int lenb = b.size(); int len = abs(lena-lenb); string append(len,‘0‘); if(lena>lenb){ b = append + b; c.resize(lena,‘0‘); }else{ a = append + a; c.resize(lenb,‘0‘); } for(int j=c.size()-1;j>=0;j--){ int current = (a[j]-‘0‘) ^(b[j]-‘0‘) ^flag; if((a[j]-‘0‘) +(b[j]-‘0‘) +flag >1) flag = 1; else flag = 0; c[j] = current+‘0‘; } if(flag == 1) c = ‘1‘+ c; return c; } };
我自己写了C的,改了好多次才成功
char *addBinary(char *a, char *b) { int flag = 0,temp,num; int i = 0; int alen = strlen(a)-1; int blen = strlen(b)-1; char *c =(char*) malloc(alen>blen? alen + 1 : blen + 1); while(alen >= 0 && blen >= 0){ num = (a[alen--]-‘0‘)+(b[blen--]-‘0‘)+flag; flag = num/2; num = num%2; c[i++] = (char)(num + ‘0‘); } while(alen >=0){ int num = a[alen--] - ‘0‘ + flag; flag = num / 2; num %= 2; c[i++] = (char)(num + ‘0‘); } while(blen >=0){ int num = b[blen--] - ‘0‘ + flag; flag = num / 2; num %= 2; c[i++] = (char)(num + ‘0‘); } if(flag > 0){ c[i++] = (char)(flag + ‘0‘); } c[i] = ‘\0‘; for(i = 0; i<(strlen(c)/2); i++){ temp = c[i]; c[i] = c[strlen(c)-i-1]; c[strlen(c)-i-1] = temp; } return c; }
其中c[i++]不能写成*c = (char)(num + ‘0‘); c++; 因为遇到"0"和"0",给*c的是0,相当于截止符‘\0‘,最后输出的是"".一直报错。
标签:
原文地址:http://www.cnblogs.com/zhhc/p/4353036.html