1 条题解
-
0
【例43.3】 转二进制
解题思路
反复输出n%2再整除2,取出的顺序就是低位到高位,正好符合题目要求。
正确性说明
计算规则直接来自题目定义。按所述顺序处理时,已完成部分的结果被准确保存在累加量、计数或当前状态中;下一步只加入新增贡献。最终得到完整要求的结果。
易错点
本题不能反转所得数字串。
复杂度
时间O(log n),空间O(1)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); long long n; cin >> n; do { cout << n % 2; n /= 2; } while (n); cout << "\n"; return 0; }
- 1