tags:

views:

85

answers:

3

Efficient way to determine if the number has identical digits in C

A: 

Probably you would want to convert it to string first (so you can easily work with digits of a number). And then apply whatever usual string algorithms you want.

+1  A: 

if its just for repeating occurances in decimal within the same number :-

int contains_repeat(int x)
{
    int occurances = 0;
    while(x>0)
    {
          if(occurances & 1 << (x % 10)) return 1;
          occurances |= 1 << (x % 10);
          x = x / 10;
    }
    return 0;
}

if its all the same

int all_the_same(int x)
{
    int digit = x%10;
    while(x>0)
    {
        if(x%10 != digit) return 0;
        x = x/10;
    }
    return 1;
}

if you want it for a different base, just pass "int base" in and use base instead of 10.

Keith Nicholas
A: 

Example:

if (4444 % 1111 == 0) // all digits are the same
Nick D