Add Binary -- leetcode
来源:互联网 发布:mac查看后台运行程序 编辑:程序博客网 时间:2024/06/03 11:09
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
二进制相加,类同与字符串相加
#include <iostream>#include <string>using namespace std;string addBinary(string a, string b) { int i = a.size() - 1;//字符串a的长度 int j = b.size() - 1;//字符串a的长度 int sum = 0;//当前位的和 int temp = 0;//进位标志 string ans;//结果字符串 while (i >= 0 && j >= 0) {//从末位开始加操作 sum = (a[i--] - '0') + (b[j--] - '0') + temp; temp = sum / 2;//求出进位 sum %= 2;//求出当前位的值 ans.insert(ans.begin(), sum + '0');//插入到字符串的最前面 } //a字符串有剩余 while (i >= 0) { int sum = (a[i--] - '0' + temp); ans.insert(ans.begin(), (sum % 2) + '0'); temp = sum / 2; } //b字符串有剩余 while (j >= 0) { int sum = (b[j--] - '0' + temp); ans.insert(ans.begin(), (sum % 2) + '0'); temp = sum / 2; } //进位标示为1,再次进位 if (temp == 1) { ans.insert(ans.begin(), (temp + '0')); } return ans;}int main() { string s; string s1; while (cin >> s >> s1) { cout << addBinary(s, s1) << endl; } system("pause"); return 0;}
扩展:任意进制(<=10)的字符串相加:
#include <iostream>#include <string>using namespace std;string addStr(string a, string b, int num) {//num表示进位 int i = a.size() - 1;//字符串a的长度 int j = b.size() - 1;//字符串a的长度 int sum = 0;//当前位的和 int temp = 0;//进位标志 string ans;//结果字符串 while (i >= 0 && j >= 0) {//从末位开始加操作 sum = (a[i--] - '0') + (b[j--] - '0') + temp; temp = sum / num;//求出进位 sum %= num;//求出当前位的值 ans.insert(ans.begin(), sum + '0');//插入到字符串的最前面 } //a字符串有剩余 while (i >= 0) { int sum = (a[i--] - '0' + temp); ans.insert(ans.begin(), (sum % num) + '0'); temp = sum / num; } //b字符串有剩余 while (j >= 0) { int sum = (b[j--] - '0' + temp); ans.insert(ans.begin(), (sum % num) + '0'); temp = sum / num; } //进位标示为1,再次进位 if (temp == 1) { ans.insert(ans.begin(), (temp + '0')); } return ans;}int main() { string s; string s1; int n; while (cin >> s >> s1) { cout << "请输入进制:"; cin >> n; cout << addStr(s, s1, n) << endl; cout << "------" << endl; } system("pause"); return 0;}
如有错误,欢迎指正,谢谢!
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
- 第十四章总结
- mysql windows导入sql文件报 gone alway
- java 等腰三角形 直角三角形 九九乘法表 关键代码
- MD5加密-使用LR javauser协议实现
- 给老白写的一个工具函数 PHP打印匹配行
- Add Binary -- leetcode
- Android:SoundPool简单介绍
- UItextview点击回车收回键盘、控制输入字数等
- sublime text使用之 ctags
- Ping命令原理
- 挑选最终的linux发行版
- Accp 7.0 第14章 示例4 可用作参考
- tortoiseGit 坑爹记
- 解决 chrome 37 之后 flash 版本过低问题