В моей интерпретации вашего вопроса я предположил, что вы хотите беззнаковое число - хотя я предполагаю, что это должно работать с целыми числами так же, как и.
Другое предположение, что я хочу сказать, что вы хотите, чтобы пользователь вводил числа как единицы и нули, которые помещаются в строку, а затем преобразуются в целое число unsigned
по функции convertBinaryNumberStringToInt
.
Здесь приведен код, указывающий, как вы могли бы это сделать, включая функцию 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;
}