Algorithm-二进制相加
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <iostream> #include <cstring> #include <string>
using namespace std;
class Solution { public: string addBinary(string ls, string rs) { int l_sz = ls.length(); int r_sz = rs.length(); string ans = ""; int tmp = 0; int added = 0; int big_sz = l_sz > r_sz ? l_sz : r_sz; for (int i = 0; i < big_sz || added; i++) { tmp = added; if (i < l_sz) { tmp += ls[l_sz - 1 - i] == '1' ? 1 : 0; } if (i < r_sz) { tmp += rs[r_sz - 1 - i] == '1' ? 1 : 0; } if (tmp >= 2) { added = 1; } else { added = 0; }
if (tmp & 1) { ans = '1' + ans; } else { ans = '0' + ans; } printf("i=[%d] tmp=%d added=%d ans=%s\n", i, tmp, added, ans.c_str()); } return ans; } };
int main() { string str_a, str_b; cin >> str_a; cin >> str_b; Solution a; cout << a.addBinary(str_a, str_b) << endl;
return 0; }
|
Review【TED演讲】在健康时讨论死亡
在活着的时候立好遗嘱,让自己以自己希望的方式被埋葬,被处理,完全自己的最后的爱与和平
计划好的事情,总会多一些内心的从容和平静
• 我们曾如此渴望命运的波澜
• 到最后才发现
• 人生最曼妙的风景
• 竟是內心的淡定与从容…
Tips
Django实现任意文件上传(最简单的方法)
Share-二进制相乘
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| #include <string> #include <cstring> #include <iostream> using namespace std;
bool is_zore(string str) { int sz = str.length(); for (int i = 0; i < sz; i++) { if (str[i] == '1') { return false; } } return true; }
string add_bin_str(string ls, string rs) { int l_sz = ls.length(); int r_sz = rs.length(); string ans = ""; int tmp = 0; int added = 0; int big_sz = l_sz > r_sz ? l_sz : r_sz; for (int i = 0; i < big_sz || added; i++) { tmp = added; if (i < l_sz) { tmp += ls[l_sz - 1 - i] == '1' ? 1 : 0; } if (i < r_sz) { tmp += rs[r_sz - 1 - i] == '1' ? 1 : 0; } if (tmp >= 2) { added = 1; } else { added = 0; }
if (tmp & 1) { ans = '1' + ans; } else { ans = '0' + ans; } } return ans; }
int main(){ string str, ls, rs; cin >> str; int pos = str.find_first_of(';'); if (pos == string::npos) { printf("invalid input\n"); return -1; }
ls = str.substr(0, pos); rs = str.substr(pos + 1, str.length() - pos - 1);
int sz = ls.length(); if (is_zore(ls) || is_zore(rs)) { puts("0"); return 0; }
string ans = ""; for (int i = sz - 1, j = 0; i > -1; i--, j++) { if (ls[i] == '1') { ans = add_bin_str(ans, rs + string(j, '0')); } } cout << ans << endl; return 0; }
|