1 条题解
-
0
练35.4 奶牛的数字游戏
解题思路
严格模拟奇数乘3加1、偶数除2,每更新一次计1分,达到1停止。
正确性说明
按上述推导执行:每次仅处理当前输入或当前步骤,并把它对答案的贡献计入对应状态。所有需要处理的情况均被覆盖,结束时保存的量就是题目所求。
易错点
初始1时得0分;只计变化次数,不计初始数。
复杂度
变化步数k,时间O(k),空间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; int ans = 0; while (n != 1) { if (n % 2) n = n * 3 + 1; else n /= 2; ans++; } cout << ans << "\n"; return 0; }
- 1