LEETCODE: Add Binary
来源:互联网 发布:.group域名为什么不火 编辑:程序博客网 时间:2024/05/21 17:11
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
class Solution {public: string addBinary(string a, string b) { int longstr = a.length() > b.length() ? a.length() : b.length(); int shortstr = a.length() < b.length() ? a.length() : b.length(); string result(longstr + 1, '0'); int jinwei = 0; int ii = 0; //Calculate if both string has value. for(; ii < shortstr; ii ++) { int sum = a[a.length() - 1 - ii] - '0' + b[b.length() - 1 - ii] -'0' + jinwei; if(sum >= 2) { jinwei = 1; sum = sum % 2; } else { jinwei = 0; } result[result.length() - 1 - ii] = sum + '0'; } //Calculate the remain string. string &remain = a.length() > b.length() ? a : b; for(; ii < longstr; ii ++) { int sum = remain[remain.length() - 1 - ii] - '0' + jinwei; if(sum >= 2) { jinwei = 1; sum = sum % 2; } else { jinwei = 0; } result[result.length() - 1 - ii] = sum + '0'; } //Set if there is jinwei. if(jinwei == 1) { result[0] = '1'; } else { result = result.substr(1, result.length() - 1); } return result; }};
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
- 前端优化《二》---关于编写性能高效的javascript事件的技术
- mysql基础(四) Mysql自增ID的设置和修改
- 内部类
- linux 在字符界面中如何查看超出屏幕显示范围的内容?
- 第十七周项目4-日期结构体(2)
- LEETCODE: Add Binary
- 使用Spring的NamedParameterJdbcTemplate完成DAO操作
- iOS 获取wifi ssid 名称
- hdu3530 Subsequence 单调队列
- java中hashset()和equals()详解
- 最简单的视频编码器:基于libx264(编码YUV为H.264)
- Unity物体拖动
- Gson简易使用小结
- Android 自定义progressDialog实现