Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get my program to do anything when a "multidigit number with all digits identical" appears?

my program generates random numbers with up to 6 digits with

int number = arc4random % 1000000;

I want that my program do something when a number like 66 or 4444 or 77777 appears (multidigit number with all digits identical). I could manual write:

    switch (number) {
    case 11: blabla...;
    case 22: blabla...;
    (...)
    case 999999: blabla;
}

That would cost me many program code. (45 cases...)

Is there an easy way to solve the problem.

like image 618
Flocked Avatar asked Jan 03 '10 04:01

Flocked


1 Answers

Here's one way to check that all digits are the same:

bool AllDigitsIdentical(int number)
{
    int lastDigit = number % 10;
    number /= 10;
    while(number > 0)
    {
        int digit = number % 10;
        if(digit != lastDigit)
            return false;
        number /= 10;
    }

    return true;
}
like image 69
Adam Rosenfield Avatar answered Oct 17 '22 00:10

Adam Rosenfield