简体   繁体   中英

How to find number in long int with binary representing? C++

If we have classical decimal format in int long, we can do something like that:

const long int NUMBER = 4577;         
const long int DIGIT_TO_FIND = 5;

long int thisNumber = NUMBER >= 0 ? NUMBER : -NUMBER; 
long int thisDigit;

while (thisNumber != 0)
{
    thisDigit = thisNumber % 10;    
    thisNumber = thisNumber / 10;    
    if (thisDigit == DIGIT_TO_FIND)
    {
        printf("%d contains digit %d", NUMBER, DIGIT_TO_FIND);
        break;
    }
}

But what about binary representing or octal representing in int long ? We have:

const long int NUMBER = 01011111; // octal
const long int DIGIT_TO_FIND1 = 0;         
const long int DIGIT_TO_FIND2 = 1;

Correct input :

01010101
11111111

Bad input :

02010101 (because two)
00000009 (because nine)

We need to check if int long contains only 0 or 1 . What is the simpliest way to check correct input for that? Maybe just easy question, but no idea, thank you.

To check whether a digit is a valid binary digit, compare it with 1 :

if (thisDigit > 1)
{
    printf("%d contains digit %d", NUMBER, thisDigit);
    break;
}

As noted by @Pubby, you have an octal number instead of a decimal number, so use 8 instead of 10 to calculate digits:

thisDigit = thisNumber % 8;    
thisNumber = thisNumber / 8;    

If I understand your question something like this -

#include <iostream>

bool check(int number, int search_1, int search_2)
{
    while(number > 0)
    {
        int digit = number % 10;
        number    = number / 10;
        if (digit != search_1 && digit != search_2)
            return false;
    }
    return true;
}

int main()
{
    const int DIGIT_TO_FIND1 = 0;
    const int DIGIT_TO_FIND2 = 1;

    int number1 = 1001001;
    std::cout << "Checking " << number1 << " : " << check(number1, DIGIT_TO_FIND1, DIGIT_TO_FIND2) <<" \n";

    int number2 = 12110101;
    std::cout << "Checking " << number2 << " : " << check(number2, DIGIT_TO_FIND1, DIGIT_TO_FIND2) <<" \n";
}

My solution. It's really simple.

   bool check(int long number)
   {
     return ((number % 10 != 0) && (number % 10) != 1);
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM