ファイルからデータを読み込もうとしていますin.txt
が、いくつかの計算の後、出力をに書き込んでいますout.txt
の最後に余分な 7 があるのはなぜout.txt
ですか?
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 は 2 進数では「101」であり、その補数は整数 2 である「010」です。
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