题目描述
对于一个数n,如果是偶数,就把n砍掉一半;如果是奇数,把n变成 3*n+ 1后砍掉一半,直到该数变为1为止。 请计算需要经过几步才能将n变到1,具体可见样例。
输入描述:
测试包含多个用例,每个用例包含一个整数n,当n为0 时表示输入结束。(1<=n<=10000)
输出描述:
对于每组测试用例请输出一个数,表示需要经过的步数,每组输出占一行。
示例1
输入
3
1
0
输出
5
0
#include <iostream>
using namespace std;
int cnt[10001];
void initialize() {
cnt[0] = 0;
cnt[1] = 0;
for (int i = 0; i <= 10000; i++) {
cnt[i] = -1;
}
}
int getRes(int n) {
if (n == 1) {
return 0;
}
if (cnt[n] != -1) {
return cnt[n];
}
if (n % 2 == 0) {
cnt[n] = getRes(n / 2) + 1;
} else if (n % 2 == 1) {
int newNum = (3 * n + 1 ) / 2;
cnt[n] = getRes(newNum) + 1;
}
return cnt[n];
}
int main() {
int n;
initialize();
while(cin >> n && n != 0) {
cout << getRes(n) << endl;
}
}