LeetCode - 67. Add Binary
来源:互联网 发布:中国网络全世界最自由 编辑:程序博客网 时间:2024/06/05 20:22
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) { string binary[] = { "0", "1" }; string ans = ""; int aSize = a.size(); int bSize = b.size(); if( aSize > bSize ) { for( int i = 0; i < aSize - bSize; i++ ) { b = binary[0] + b; } } if( bSize > aSize ) { for( int i = 0; i < bSize - aSize; i++ ) { a = binary[0] + a; } } int i = aSize > bSize ? aSize - 1 : bSize - 1; int r = 0; while( i >= 0 ) { int aNum = a[i] - '0'; int bNum = b[i] - '0'; int num = aNum + bNum + r; if( num > 1 ) r = 1; else r = 0; num = num % 2; ans = binary[num] + ans; i--; } if( r == 1 ) { ans = binary[1] + ans; } return ans; }};
0 0
- [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
- 67. Add Binary LeetCode
- 【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-67.Add Binary
- 四个月的蜕变之UDP和TCP的简单实现和基本流程
- 【NOIP2014八校联考第4场第1试10.19】无聊的游戏(game)
- Linux菜鸟的入门-常用命令13个
- Ubuntu一键安装Android Studio
- 协同过滤算法
- LeetCode - 67. Add Binary
- JavaScript继承
- CSS 外边距(margin)重叠及防止方法
- 【Dongle】【Java】规范之JDBC
- poj3734(矩阵幂)
- java的HashCode方法
- 自定义tablayout
- 又一版A+B
- 元素居中的几种方法