1 条题解
-
0
【深基4.例4】一尺之棰
解题思路
第一天记为 1,只要长度还大于 1 就整除 2,并把天数加一。
正确性说明
每次循环精确模拟从当天到次日的变化,终止时长度首次变成 1,对应计数就是所求天数。
易错点
长度为 1 时答案是第一天;整数除法自动向下取整。
复杂度
时间 O(log a),空间 O(1)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int a; cin >> a; int day = 1; while (a > 1) { a /= 2; day++; } cout << day << "\n"; return 0; }
- 1