2 条题解
-
0
参考答案:
#include<iostream> using namespace std; const int N = 1010; int a[N], b[N], ans[N]; int main() { int A, B; cin >> A >> B; int cnt = 0; while(A) { a[cnt ++] = A % 2; A /= 2; } int t = cnt - 1; cnt = 0; while(B) { b[cnt ++] = B % 2; B /= 2; } t = max(t, cnt - 1); for(int i = t; i >= 0; -- i ) ans[i] = a[i] + b[i]; for(int i = t; i >= 0; -- i ) cout << ans[i]; return 0; }
-
0
参考答案 c++
简单版 :
#include<iostream> using namespace std; const int N = 1010; int a[N], b[N], ans[N]; int main() { int A, B; cin >> A >> B; int cnt = 0; while(A) { a[cnt ++] = A % 2; A /= 2; } int t = cnt - 1; cnt = 0; while(B) { b[cnt ++] = B % 2; B /= 2; } t = max(t, cnt - 1); for(int i = t; i >= 0; -- i ) ans[i] = a[i] + b[i]; for(int i = t; i >= 0; -- i ) cout << ans[i]; return 0; }
进阶版
#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<int> add(vector<int> &a , vector<int> &b) { if (a.size() < b.size()) return add(b ,a); int t = 0; vector<int> c; for (int i = 0 ; i < a.size() ; i ++ ) { t += a[i]; if (i < b.size()) t += b[i]; c.push_back(t % 10); t /= 10; } if (t) c.push_back(t); reverse(c.begin() , c.end()); return c; } int main() { int n , m; cin >> n >> m; string s1 , s2; while (n) { int temp = n % 2; s1 += temp + '0'; n /= 2; } while (m) { int temp = m % 2; s2 += temp + '0'; m /= 2; } vector<int> a , b; for (int i = 0 ; i < s1.size() ; i ++ ) a.push_back(s1[i] - '0'); for (int i = 0 ; i < s2.size() ; i ++ ) b.push_back(s2[i] - '0'); vector<int> c = add(a , b); for (int i = 0 ; i < c.size() ; i ++ ) cout << c[i]; return 0; }
- 1
信息
- ID
- 5400
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 8
- 标签
- 递交数
- 20
- 已通过
- 7
- 上传者