LeetCode: Add Binary

C++版

 1 class Solution {

 2 public:

 3     string addBinary(string a, string b) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         if (a.size() > b.size()) b = string(a.size()-b.size(), '0') + b;

 7         if (a.size() < b.size()) a = string(b.size()-a.size(), '0') + a;

 8         for (int i = 0; i < a.size(); i++) a[i] += int(b[i]-'0');

 9         int carry = 0;

10         for (int i = a.size()-1; i >= 0; i--) {

11             a[i] += carry;

12             carry = (a[i]-'0') / 2;

13             if (a[i] > '1') a[i] = '0' + (a[i]-'0') % 2;

14         }

15         if (carry) a = '1'+a;

16         return a;

17     }

18 };

 C#版

C#有一些好处,比如不需要'0',他会自动变成字符,还有IndexOf也带来不少好处,不好的是C#的string是readonly,不能对字符串里的单个字符进行修改。另外需要注意的是new string(char c, int n),与C++的习惯略有不同

 1 public class Solution {

 2     public string AddBinary(string a, string b) {

 3         if (a.Length < b.Length) a = new string('0', b.Length - a.Length) + a;

 4         else b = new string('0', a.Length - b.Length) + b;

 5         string ans = "";

 6         int c = 0;

 7         for (int i = a.Length-1; i >= 0; i--) {

 8             c = a[i] - '0' + b[i] - '0' + c;

 9             ans = c % 2 + ans;

10             c /= 2;

11         }

12         if (c > 0) ans = '1' + ans;

13         return ans == "0"? "0" : ans.Substring(ans.IndexOf('1'));

14     }

15 }
View Code

 

你可能感兴趣的:(LeetCode)