LeetCode67. Add Binary
来源:互联网 发布:大数据运用的案例 编辑:程序博客网 时间:2024/05/12 17:46
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 sa = a.size(); int sb = b.size(); int flag = 0,da = 0; string res; for (sa,sb;sa>0 && sb > 0;sa--,sb--) { int temp = (int)(a[sa-1]-'0') + (b[sb-1]-'0')+flag; flag = temp / 2; da = temp % 2; res.push_back(da+'0'); } while (sa) { int temp = (int)(a[sa-1]-'0')+flag; flag = temp / 2; da = temp % 2; res.push_back(da+'0'); sa--; } while (sb) { int temp = (int)(b[sb-1]-'0')+flag; flag = temp / 2; da = temp % 2; res.push_back(da+'0'); sb--; } if (flag == 1) res.push_back(flag+'0'); reverse(res.begin(),res.end()); return res; }};
0 0
- LeetCode67. Add Binary
- leetcode67:Add Binary
- LeetCode67. Add Binary
- LeetCode67. Add Binary
- LeetCode67. Add Binary
- Leetcode67. Add Binary
- LeetCode67 Add Binary
- leetcode67-Add Binary
- LeetCode67——Add Binary
- LeetCode67——Add Binary
- leetcode67---Add Binary(二进制加法)
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- 关于Java编译的问题
- Android学习笔记--Path基本操作
- 探秘中东直播市场
- strlen 与sizeof()的区别
- 珠玑妙算
- LeetCode67. Add Binary
- JAVA继承中,成员变量的访问
- Memcached和Redis对比
- gdb调试常用命令
- C++11 中std::thread和std::mutex的用法
- SQL语句操作全集
- 动态注册广播
- Linux命令行部署weblogic
- Linux Ubuntu 12.04 下安装mysql 以及创建 远程navicat 连接