题解 | #扭蛋机# 倒推计算
扭蛋机
https://www.nowcoder.com/practice/9d26441a396242a9a0f7d2106fc130c7
根据给定的N值往前倒推即可。N如果为偶数,说明是3投的;如果为奇数,说明是2投的。注意最后要反转。
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main() {
int N;
while (cin >> N) {
string ans = "";
while (N != 0) {
if (N % 2 == 0) {
ans += "3";
N = (N - 2) / 2;
} else {
ans += "2";
N = (N - 1) / 2;
}
}
reverse(ans.begin(), ans.end());
cout << ans << endl;
}
return 0;
}
时间复杂度:O(logN),其中N为输入的整数。在每次循环中,N都会被除以2,直到N变为0。因此,循环次数为logN
空间复杂度:O(logN),主要是由字符串ans所占用的空间决定的。在每次循环中,都会向字符串ans中添加一个字符,最终字符串ans的长度为logN

腾讯云智研发成长空间 229人发布