leetcode 67. Add Binary
2016-04-15 21:08
323 查看
题意
两个字符串存放一个整数的二进制位,返回相加后的数的字符串表示题解
如题代码
class Solution { public: string addBinary(string a, string b) { string result; //int minsize = min(a.length(), b.length()); int carry = 0; int i = a.length() - 1, j = b.length() - 1; for(; i >= 0 && j >= 0; i--, j--) { int num = a[i] - '0' + b[j] - '0' + carry; carry = num / 2; result += (num % 2 + '0'); } while(i >= 0) { int num = a[i] - '0' + carry; carry = num / 2; result += (num % 2 + '0'); i--; } while(j >= 0) { int num = b[j] - '0' + carry; carry = num / 2; result += (num % 2 + '0'); j--; } if(carry) result += '1'; reverse(result.begin(), result.end()); return result; } };
相关文章推荐
- MAC 下安装 SVN
- winxp可以禁用的服务
- 【一天一道LeetCode】#18. 4Sum
- 【一天一道LeetCode】#18. 4Sum
- ZOJ 3802 Easy 2048 Again(状压DP)
- Lightoj1247 (博弈+NIM)
- C++11多线程教学(二)
- "围观"设计模式(2)--里氏替换原则(LSP,Liskov Substitution Principle)
- BroadCastReceiver 简介
- 我的博客
- 编译原理—Lex简单使用
- C++11多线程教学(一)
- NYOJ 990 蚂蚁感冒
- Maven编译apache falcon_win10
- ZOJ 3752 The Three Guys(暴力)
- java入门
- UCOSIII怎么配置的时钟?(时钟源头选择,倍频)
- JS实现《黑客帝国》落地字母背景
- C++性能的优化
- CF 546A Soldier and Bananas