私はあなたが未署名の数をしたいと仮定 - 私はこれは符号付き整数で動作する必要がありますねかかわらずまあまあ。
もう1つの前提は、数字を1と0として入力し、文字列に入れて、convertBinaryNumberStringToInt
で整数unsigned
に変換することです。
あなたの番号のバイナリ形式で何個あるのかを数えるために特別に作られたhowManyOnes
という機能を含め、あなたができることを示唆するいくつかのコードがあります。
#include <iostream>
#include <string>
// For CHAR_BIT
#include <climits>
// For std::reverse, but you could
// write your own string reverse function
#include <algorithm>
unsigned convertBinaryNumberStringToInt(const std::string& stringNumber)
{
unsigned outputNumber = 0;
// Using a reversed string allows us to insert ones in the
// number's binary form from right to left while still using
// a range-based for loop with not much tinkering
std::string reversedStrNum = stringNumber;
std::reverse(reversedStrNum.begin(), reversedStrNum.end());
unsigned i = 1;
// i starts as 00000000000000000000000000000001 (binary, assuming 32 bits integer)
// On each iteration of the for loop, the 1 is shifted left and,
// if the current character is '1', the value 1 is copied into
// its corresponding current position in outputNumber
for(char c : reversedStrNum)
{
if(c == '1')
{
// The bitwise-or operation copies the 1 in i to
// its corresponding position in outputNumber
outputNumber = outputNumber | i;
}
// Shift i's 1 to the left by one position
i = i << 1;
// You could also do i *= 2, but we're specifically shifting
// bits, so the bitshift seems more "semantic"
}
return outputNumber;
}
bool isStringCorrect(std::string& userString, size_t maxSize)
{
if(userString.size() > 9)
return false;
for(char c : userString)
if(c != '1' && c != '0')
return false;
return true;
}
unsigned computerGuess(unsigned highBound)
{
return rand() % highBound;
}
unsigned howManyOnes(unsigned number)
{
unsigned count = 0;
unsigned shifter = 1;
// For each bit: sizeof(unsigned) is the size in bytes
// of an unsigned, CHAR_BIT is the bit length of a char or byte
// So we loop through each bit position.
for(unsigned i = 0; i < CHAR_BIT * sizeof(unsigned); i++)
{
// What we do is we test our number against the shifter
// for each bit position. If a bitwise-and between both
// is non-zero, it means number has 1 in that position,
// so we increase the "one" count.
if((number & shifter) != 0)
++count;
// Either way, we left-shift the one in shifter afterwards
shifter = shifter << 1;
}
return count;
}
int main()
{
std::string userChoiceNumberString;
std::cout << "Enter a number: ";
std::cin >> userChoiceNumberString;
if(!isStringCorrect(userChoiceNumberString, 9))
{
std::cout << "Entered string is incorrect" << std::endl;
return -1;
}
unsigned userChoiceNumber = convertBinaryNumberStringToInt(userChoiceNumberString);
std::cout << "Your number has " << howManyOnes(userChoiceNumber) << " ones in binary." << std::endl;
int attempts = 7;
while(attempts > 0)
{
if(computerGuess(512) == userChoiceNumber)
{
std::cout << "Yeeha! I won!" << std::endl;
attempts = 0;
}
else
{
std::cout << "Hmmm... guessed wrong..." << std::endl;
--attempts;
}
}
return 0;
}