leetcode 67Add Binary
来源:互联网 发布:湖北大学知行学院校花 编辑:程序博客网 时间:2024/05/06 03:28
Add Binary
My SubmissionsTotal Accepted: 55613 Total Submissions: 225733 Difficulty: Easy
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Show Similar Problems
和做十进制加法一样,要考虑进位。
// test67AddBinary.cpp : 定义控制台应用程序的入口点。
///*
情况说明,主要是处理a,b一样长,以及不等长的情况。
等长情况下,是否有进位。
不等长情况下,是否有进位
*/
#include "stdafx.h"
#include "string"
using std::string;
string addBinary(string a, string b);
int _tmain(int argc, _TCHAR* argv[])
{
string s = addBinary("100", "101");
return 0;
}
string addBinary(string a, string b)
{
int signal = 0;
string result = "";
int anum = 0, bnum = 0;
int alength = a.size();
int blength = b.size();
char temp;
while (alength > 0 && blength > 0)
{
alength--;
blength--;
anum = a[alength]-48;
bnum = b[blength]-48;
temp = (anum + bnum + signal) % 2+48;
signal = (anum + bnum + signal) / 2;
result = temp + result;
}
if (alength > 0)
{
while (alength>0)
{
alength--;
anum = a[alength] - 48;
temp = (anum + signal) % 2 + 48;
signal = (anum + signal) / 2;
result = temp + result;
}
if (signal > 0)
{
temp = signal + 48;
result = temp + result;
signal = 0;
}
}
if (blength > 0)
{
while (blength>0)
{
blength--;
bnum = b[blength] - 48;
temp = (bnum + signal) % 2 + 48;
signal = (bnum + signal) / 2;
result = temp + result;
}
if (signal > 0)
{
temp = signal + 48;
result = temp + result;
signal = 0;
}
}
if (signal > 0)
{
temp = signal + 48;
result = temp + result;
}
return result;
}
0 0
- [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
- leetcode 67 Add Binary
- [leetcode 67] Add Binary
- Android 将软键盘的回车按钮改变成搜索按钮
- Linux下的一些查看命令
- seo优化注意
- ML-评判标准
- 模拟集成电路学习心得(不见牛人,不懂世界之大!!!)
- leetcode 67Add Binary
- 平衡二叉树 之 红黑树
- 从控制面板卸载SQL2012,是否会删除注册表项和文件夹
- 小知识
- 《快学Scala》 第2章 控制结构和函数
- 阅读《Android 从入门到精通》(6)——按钮
- javascript。。。。。。。
- 可以这样去理解group by和聚合函数
- caishuzi