首页 > 代码库 > 【leetcode】Add Binary

【leetcode】Add Binary

Add Binary 

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

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

 

Hide Tags
  Math String
 
 
先补全字符串,从末尾开始加,每次计算当前位和进位即可
 1 class Solution { 2 public: 3     char addBit(char a,char b,char &c) 4     { 5         if(a==b&&a==1) 6         { 7             char ret; 8             ret=c; 9             c=1;10             return ret;11         }12         else if(a==b&&a==0)13         {14             15             if(c==0)16             {17                 return 0;18             }19             else20             {21                 c=0;22                 return 1;23             }24         }25         else26         {27             if(c==1)28                return 0;29             else30                return 1;31             32         }33     }34     35     string addBinary(string a, string b) {36         37         int na=a.length()-1;38         int nb=b.length()-1;39         40         if(na!=nb)41         {42             string tmp(abs(na-nb),0);43             if(na>nb)44                 b=tmp+b;45             else46                 a=tmp+a;47         }48         49         int i=a.length()-1;50         string result(a.length(), 1);51         char c=0;52         53         while(i>=0)54         {55             result[i]=addBit(a[i],b[i],c);56             i--;57         }58         if(c==0)59         {60             return result;61         }62         else63         {64             return 1+result;65         }66     }67 };

 

 

【leetcode】Add Binary