【发布时间】:2021-12-28 05:04:16
【问题描述】:
我正在尝试从文件in.txt 读取数据,经过一些计算,我将输出写入out.txt
为什么out.txt的末尾多了一个7?
Solution 类的内容。
class Solution
{
public:
int findComplement(int num)
{
int powerof2 = 2, temp = num;
/*
get number of bits corresponding to the number, and
find the smallest power of 2 greater than the number.
*/
while (temp >> 1)
{
temp >>= 1;
powerof2 <<= 1;
}
// subtract the number from powerof2 -1
return powerof2 - 1 - num;
}
};
main 函数的内容。
假设所有标题都包括在内。 findComplement 翻转数字的位。例如,整数 5 在二进制中是“101”,其补码是“010”,即整数 2。
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
// helper variables
Solution answer;
int testcase;
// read input file, compute answer, and write to output file
while (std::cin) {
std::cin >> testcase;
std::cout << answer.findComplement(testcase) << "\n";
}
return 0;
}
in.txt的内容
5
1
1000
120
out.txt的内容
2
0
23
7
7
【问题讨论】: