LeetCode 第 67 题 (Add Binary)
来源:互联网 发布:出租淘宝号的平台 编辑:程序博客网 时间:2024/04/28 10:03
LeetCode 第 67 题 (Add Binary)
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
两个字符串,计算加法。这道题主要是考察对字符串操作的掌握情况。另外,加法要从低位算起,但是输出时要先输出高位。因此,需要将计算结果先存下来,然后再逆序输出。
访问字符串的字符可以采用传统的 c 语言那种数组下标的方式。也可以用 iterator。
下标方式的代码如下:
string addBinary(string a, string b){ int n1 = a.length() - 1; int n2 = b.length() - 1; char ai, bi, ci, carry = 0; stack<char> out; while (n1 >= 0 || n2 >= 0) { ai = (n1 >= 0) ? a[n1--] - '0' : 0; bi = (n2 >= 0) ? b[n2--] - '0' : 0; ci = ai + bi + carry; carry = (ci > 1) ? 1 : 0; ci = ci & 0x01; out.push(ci); } if(carry > 0) out.push(carry); string c; while(!out.empty()) { ci = out.top() + '0'; c.push_back(ci); out.pop(); } return c;}
iterator 方式有点特殊,对字符串逆序遍历需要用 reverse_iterator。代码如下:
string addBinary(string a, string b){ string::const_reverse_iterator ita = a.crbegin(); string::const_reverse_iterator itb = b.crbegin(); char ai, bi, ci, carry = 0; stack<char> out; while (ita != a.crend() || itb != b.crend()) { ai = (ita != a.crend()) ? *ita++ - '0' : 0; bi = (itb != b.crend()) ? *itb++ - '0' : 0; ci = ai + bi + carry; carry = (ci > 1) ? 1 : 0; ci = ci & 0x01; out.push(ci); } if(carry > 0) out.push(carry); string c; while(!out.empty()) { ci = out.top() + '0'; c.push_back(ci); out.pop(); } return c;}
1 0
- LeetCode 第 67 题 (Add Binary)
- 【leetcode】第67题 Add Binary 题目+解析+JAVA代码
- [leetcode 67] Add Binary
- [LeetCode 67]Add Binary
- leetcode-67 Add Binary
- leetcode || 67、Add Binary
- LeetCode 67 Add Binary
- Add Binary - LeetCode 67
- LeetCode---(67) Add Binary
- leetcode[67]:Add Binary
- leetcode 67 Add Binary
- Leetcode# 67 Add Binary
- leetcode 67: Add Binary
- leetcode-67-Add Binary
- Leetcode#67||Add Binary
- [Leetcode]#67 Add Binary
- leetcode 67Add Binary
- Leetcode 67:Add Binary
- 在Linux上部署Java访问MongoDB
- 贩妖记 > 第七十九章,人质
- 2.Oracle数据类型
- 【Java进阶二】理解继承
- Android插件化浅析
- LeetCode 第 67 题 (Add Binary)
- R-CNN随笔No.3
- 3.Oracle SQL函数
- 侧拉删除
- 4.Oracle表空间
- ubuntu sudo apt-get update 失败
- MySQL Server 5.7 安装记录
- 基于历史数据查询的爬虫操作
- ubunbu中文输入法安装