Leetcode -- Add Binary
来源:互联网 发布:艾克里里淘宝店号码 编辑:程序博客网 时间:2024/06/07 03:21
题目:
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.、
分析:
就是这么简单,二进制相加
代码:
string addBinary(string a, string b) { string str = ""; int len1 = a.size(); int len2 = b.size(); int count = 0; int i= len1 - 1; int j =len2 - 1; int c1, c2, sum; while(i>= 0 || j >= 0) { if(i>=0 && j >= 0) { c1 = a[i] - '0'; c2 = b[j] - '0'; sum = c1 + c2 + count; if(sum == 3) { count = 1; str = '1' + str; } if(sum == 2) { count = 1; str = "0" + str; } if(sum == 1) { count = 0; str = "1" + str; } if(sum == 0) { count = 0; str = "0" + str; } i --; j --; } else { if(i>=0) { c1 = a[i] - '0'; sum = count + c1; if(sum == 2) { count = 1; str = "0" + str; } else { if(sum == 1) str = "1" + str; if(sum == 0) str = "0" + str; count = 0; } i--; } if(j >= 0) { c1 = b[j] - '0'; sum = count + c1; if(sum == 2) { count = 1; str = "0" + str; } else { if(sum == 1) str = "1" + str; if(sum == 0) str = "0" + str; count = 0; } j --; } } } if(count > 0) { str = "1" + str; } return str; }
简短版:
引自:Discussion
class Solution{public: string addBinary(string a, string b) { string s = ""; int c = 0, i = a.size() - 1, j = b.size() - 1; while(i >= 0 || j >= 0 || c == 1) { c += i >= 0 ? a[i --] - '0' : 0; c += j >= 0 ? b[j --] - '0' : 0; s = char(c % 2 + '0') + s; c /= 2; } return s; }};
注意:写代码一定要认真啊
0 0
- LeetCode: Add Binary
- [Leetcode] Add Binary
- LeetCode Add Binary
- Leetcode: Add Binary
- [Leetcode] Add Binary
- LeetCode : Add Binary
- LeetCode Add Binary
- [LeetCode] Add Binary
- leetcode 58: Add Binary
- leetcode Add Binary
- [LeetCode] Add Binary
- 【leetcode】Add Binary
- [LeetCode]Add Binary
- [leetcode]Add Binary
- LeetCode-Add Binary
- [leetcode] Add Binary
- LeetCode - Add Binary
- leetcode:Add Binary
- hdoj 1285 确定比赛名次
- java基础-API-String类、基本数据类型对象包装类
- Unity插件之Kolmich(教你如何快速搭建一个完整的小地图)
- UVa 1612:Guess(贪心)
- BZOJ1053
- Leetcode -- Add Binary
- 黑马程序员----Java中的IO流学习笔记1
- 如何在C++类中安全地使用多线程中的处理函数
- passport登陆的实现--跨域共享cookie和跨域共享session
- hdu 4533(树状数组)
- 黑马程序员--说好了的反射!
- Java修饰符关键词大全
- shell-字符截取命令sed
- InterlockedIncrement内部是如何实现的?