再贴一遍,真的很难受。。。 #include <iostream> #include <string> #include <algorithm> using namespace std; int main() { unsigned long long n; cin >> n; if (n == 0) { cout << 1 << endl; return 0; } else if (n == 1 || n == 2) { cout << 2 << endl; return 0; } else if (n == 3) { cout << 3 << endl; return 0; } string binaryForm; bool flag = false; for (unsigned long long i = (long long)1 << 63; i != 0; i = i >> 1) { if (i & n) { binaryForm += '1'; flag = true; } else { if (flag) { binaryForm += '0'; } } } int length = binaryForm.size(); long long count = 1; int curr = 1; for (int i = 0; i < length - 1; i++) { if (i % 2 == 0 && i != 0) { curr *= 2; } count += curr; } string subLeft = binaryForm.substr(1, (length - 1) / 2); int times = 1; for (int i = subLeft.size() - 1; i >= 0; i--) { if (subLeft[i] == '1') { count += times; } times *= 2; } string newBinaryForm = "1" + subLeft; if (length % 2) { subLeft.pop_back(); } reverse(subLeft.begin(), subLeft.end()); newBinaryForm += subLeft + "1"; if (newBinaryForm <= binaryForm) { count++; } cout << count << endl; return 0; }
点赞 4
牛客网
牛客企业服务