Leetcode9: Add Binary
来源:互联网 发布:excel大批量数据查找 编辑:程序博客网 时间:2024/06/17 07:29
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
看看自己写的代码,渣的不行。把string先转成数字,相加后再对每一位判断是否大于1,最后生成的数字再转成string,真是完全不把string当回事啊~~为什么不直接在string上操作呢?而且转化为int,还有上限的问题,比如输入这两个"1110110101", "1110111011" ,结果是:"-1226763192"而不是"11101110000"!!真是被自己蠢哭~~
class Solution {public: string addBinary(string a, string b) { int Inta = atoi(a.c_str()); int Intb = atoi(b.c_str()); int c = Inta + Intb; vector<int> temp; int flag = 0; int d; while(c) { d = c % 10; flag = d / 2; temp.push_back(d%2); c /= 10; c += flag; } int size = temp.size(); d = 0; for(int i = size-1; i >= 0; i--) { d = d*10 + temp[i]; } char str[size]; sprintf(str, "%d", d); //_itoa(d, str, 10); string tostr(str); return tostr; }};
看看别人写的代码:
class Solution {public: string addBinary(string a, string b) { string longStr = a.length() > b.length() ? a : b; string shortStr = a.length() > b.length() ? b : a; int ad = 0; int j = longStr.length() - 1; for(int i = shortStr.length() - 1; i > -1; i--, j--) { if(shortStr[i] - '0' + longStr[j] - '0' + ad > 1) { longStr[j] = '0' + (shortStr[i] - '0' + longStr[j] - '0' + ad) % 2; ad = 1; } else { longStr[j] = '0' + shortStr[i] - '0' + longStr[j] - '0' + ad; ad = 0; } } for(; j > -1; j--) { if(longStr[j] - '0' + ad > 1) { longStr[j] = '0' + (longStr[j] -'0' + ad) % 2; ad = 1; } else { longStr[j] = '0' + (longStr[j] - '0' + ad) % 2; ad = 0; } } if(ad) { longStr.insert(0,1,'1'); } return longStr; }};自己对string的操作太不熟悉了
![再见](http://static.blog.csdn.net/xheditor/xheditor_emot/default/bye.gif)
0 0
- Leetcode9: Add Binary
- leetcode9
- leetcode9
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- JAVA API Collection and Map
- 自定义网络加载视图NetworkImageView
- Java 的 脚本语言支持
- Java中的线程
- 杭电1280(前m大的数)
- Leetcode9: Add Binary
- android sdk下载以及一些学习网站
- F - The Minimum Length HUST1010( kmp计算最小循环节)
- FrameLayout 的 margin 在 2.x 上不生效
- c++ copy constructor, operator=
- 算法-骨牌覆盖问题(矩阵快速幂求Fibonacii)
- 结构体内部偏移的妙用 从文件中按照固定格式读取数据
- 求两个等长已排序数组的中位数(算法导论习题9.3-8)
- Velocity中的if