感受一下c++20的魔法吧!由于使用了c++20,所以不能在acwing通过,但可以去洛谷提交。
洛谷题目链接:https://www.luogu.com.cn/problem/P1010
#include <algorithm>
#include <bit>
#include <format>
#include <iostream>
#include <vector>
using namespace std;
vector<int> break_down(unsigned int n) {
vector<int> res;
for (auto highbit = bit_floor(n); highbit; highbit >>= 1)
if (n & highbit)
res.push_back(countr_zero(highbit));
return res;
}
string convert(unsigned int n) {
auto parts = break_down(n);
auto wrap = [](string_view str) { return str.empty() ? "2" : format("2({})", str); };
auto early_stop = [](unsigned int x) -> string {
switch (x) {
case 0:
return "0";
case 1:
return "";
case 2:
return "2";
}
return convert(x);
};
string res = wrap(early_stop(parts.front()));
for (int i = 1; i < parts.size(); ++i)
res += "+" + wrap(early_stop(parts[i]));
return res;
}
int main() {
ios::sync_with_stdio(false);
unsigned int n;
cin >> n;
cout << convert(n);
return 0;
}
有人看我再补充思路