Add Binary
来源:互联网 发布:安邦和谐健康 知乎 编辑:程序博客网 时间:2024/06/03 06:02
c++
class Solution {public: string addBinary(string a, string b) { if (a.empty()) return b; if (b.empty()) return a; int i = a.size() - 1; int j = b.size() - 1; int update = 0; string res; while (i >= 0 && j >= 0) { update += (a[i--] - '0') + (b[j--] - '0'); res.push_back(update % 2 + '0'); update /= 2; } while (i >= 0) { update += (a[i--] - '0'); res.push_back(update % 2 + '0'); update /= 2; } while (j >= 0) { update += (b[j--] - '0'); res.push_back(update % 2 + '0'); update /= 2; } if (update == 1) res.push_back(update + '0'); reverse(res.begin(), res.end()); return res; }};
python
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ if not a: return b if not b: return a a, b = list(a), list(b) i, j = len(a)-1, len(b)-1 update = 0 res = [] while i>=0 and j>=0: update += int(a[i])+int(b[j]) res.append(str(update%2)) update /= 2 i -= 1 j -= 1 while i>=0: update += int(a[i]) res.append(str(update%2)) update /= 2 i -= 1 while j>=0: update += int(b[j]) res.append(str(update%2)) update /= 2 j -= 1 if update ==1: res.append(str(update)) return ''.join(res[::-1])
0 0
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- 移动硬盘提示需要格式化
- leetcode No1. Two Sum
- 北大青鸟asp.net学习总结——Asp.net对象之Application对象、Server对象
- jquery ajax请求成功,返回了数据,但是不进success回调函数的问题
- 手机开发实战132——SyncML介绍1
- Add Binary
- 手机开发实战133——SyncML介绍2
- 8. 使用JPA保存数据【从零开始学Spring Boot】
- 【PHP】PHP使用PHPExcel生成Excel表格文件(附带随机生成英文名函数)
- JavaI/O流
- 第十六周项目 阅读程序(6)
- 手机开发实战134——SyncML介绍3
- 在Bae上部署WebUploader出错
- (十一)javascript 动态改变元素的属性