LeetCode interview Questions:Add binay
LeetCode interview Questions:Add binay
1.int之类的数可以使用small
2.直接在字符串使用二进制的加法
http://www.leetcode.com/onlinejudge 需要FQ
class Solution {
public:
int string_to_int(string str) {
int result = 0;
int level = 1;
for(int i = str.length() - 1; i >=0 ; i--) {
if (str[i] == '1') {
result += level;
}
level <<= 1;
}
return result;
}
string int_to_string(int n) {
string result = "";
while(n) {
if(n%2==1) {
result="1" + result;
}
else {
result="0" + result;
}
n>>=1;
}
if(result.length()==0) {
result="0";
}
return result;
}
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//small
//int ai = string_to_int(a);
//int bi = string_to_int(b);
//int result = ai + bi;
//return int_to_string(result);
//large
string result;
int carray_bit = 0;
for(int i=a.length()-1,j=b.length()-1;i>=0 && j>=0; i--,j--) {
if(a[i]=='0' && b[j]=='0') {
if(carray_bit==1) {
result = "1" + result;
}
else {
result = "0" + result;
}
carray_bit=0;
}
else if( (a[i]=='0' && b[j]=='1') || (a[i]=='1' && b[j]=='0') ){
if(carray_bit==1) {
//carray_bit still 1
result = "0" + result;
}
else {
//carray_bit still 0
result = "1" + result;
}
}
else if(a[i]=='1' && b[j]=='1') {
if(carray_bit==1) {
result = "1" + result;
}
else {
result = "0" + result;
}
carray_bit = 1;
}
}
if(result.length()==0) {
result="0";
}
return result;
}
};
浙公网安备 33010602011771号