Determine if all digits are equal

Asked

Viewed 4,487 times

34

It takes as a parameter a numerical value. For example, 888 or 546. And I have a function that returns a value one boolean true if all numbers are equal, or false if they are different.

How do I proceed with the algorithm?

  • 3

    Two options: 1) turn the number into string (decimal representation, of course) and see if all characters are equal; 2) Make a series of integer divisions by 10 and the rest of the division by 10, and compare if the results are all equal.

  • 1

    'If all numbers are equal, do you mean that all digits are equal or will you get 888, 546 and test if 888 and 546 are equal? It actually makes little difference. It would be good to specify which type of data will be given as input (string, int, float, etc).

15 answers

30


A response in C#, using the method of comparing the characters of a string:

public bool TodosIguais( int num ) {
  char comparar = num.ToString()[0];
  foreach( var n in num.ToString() ) {
    if ( comparar != n ) { return false; }
  }
  return true;
}

Editing

The same answer, in a more compact way, using extension methods and LINQ:

//criar o classe
public static class Extencoes {
  public static bool TodosIguais( this int num ) {
    return num.ToString().All(c=>c.Equals(num.ToString().First()));
  }
}

//use-o
int numero = 5;
if ( numero.TodosIguais() ) { Console.WriteLine("Todos iguais."); }

29

  • Get the number of decimals of a given original number The using the formula Floor(Log10(numero)) + 1

Example:

O = 99999  
X = floor(log10(99999)) + 1 = 5 
  • Generate a number N which has the repeated digit 1 X times

Example:

N = 11111
  • Divide the original number O by N. If the division is integer, the number is a repeat.

Example:

O / N = 99999 / 11111 = 9.0 ; verdadeiro.

26

    1. Let X be the original number.
    1. Divide X by 10 and get the rest, call it R1.
    1. Repeat while X is non-zero
      • 3.1 Assign R2 the rest of the division of X by 10.
      • 3.2 If R1 is different from R2, return false.
      • 3.2 Assign X the quotient of the entire division of X by 10.
    1. Return true.

Note that this approach works using only mathematics, without having to convert the number to string at any time.

See here the above algorithm implemented in javascript, including the test code:

function digitosIguais(x) {
  var r1 = x % 10;               // Passo 2.
  while (x > 0) {                // Passo 3.
    var r2 = x % 10;             // Passo 3.1.
    if (r2 !== r1) return false; // Passo 3.2.
    x = Math.floor(x / 10);      // Passo 3.3.
  }
  return true;                   // Passo 4.
}

function teste(numero) {
  document.writeln(numero + (digitosIguais(numero) ? "" : " não") + " tem todos os dígitos iguais.<br>");
}

teste(5555);
teste(88);
teste(9);
teste(11);
teste(0);
teste(123);
teste(765);
teste(9999998);
teste(800);
teste(404);

Click on the blue button Execute above to test and observe the result.

25

Playing riddles of black magic:

1) A perl command that reads from STDIN and writes OK if all numbers are equal

perl -E 'say "OK" if <> =~ /^(\d)\1*$/'

2) an algorithm:

f(a) =  int((a*9+10)/10) % 10**(int(log10 a)) == 0
  • 2

    Excellent answer, but I think should be a =.

  • @Victorstafusa, you’re absolutely right: I got carried away by the beauty of Unicode :)

21

Javascript implementation of the provided formula in Jjoao’s answer.

Also includes the tests.

function digitosIguais(a) {
  return a === 0 || Math.floor((a * 9 + 10) / 10) % Math.pow(10, Math.floor(Math.log10(a))) === 0;
}

function teste(numero) {
  document.writeln(numero + (digitosIguais(numero) ? "" : " não") + " tem todos os dígitos iguais.<br>");
}

teste(5555);
teste(88);
teste(9);
teste(11);
teste(0);
teste(123);
teste(765);
teste(9999998);
teste(800);
teste(404);

Click on the blue button Execute above to test and observe the result.

20

With regular expressions

Using regular expressions is easy to implement this idea in any language: ^(\d)\1*$

Explaining

^ mark the beginning of the string

(\d) I get a numeric digit

\1 the following character is equal to the digit I obtained

* this character can be repeated several times, or no

$ mark the end of the string (as I am marking the beginning and the end, I guarantee there will be no extra character in the string)

Implementing in javascript

I made a function to facilitate the use

function digitosIguais(numero) {
  return !!numero.toString().match(/^(\d)\1*$/);
}

Explaining

!! is to turn the result into boleano

toString() is to convert number to string, before applying regular expression

Testing

console.log( digitosIguais(88888889) ); // => false
console.log( digitosIguais(88888888) ); // => true
  • 1

    Boy, what a regex dahora.

19

Java 8 with chars stream

In Java 8 is easy with streams:

boolean digitosIguais(Long numero) {
    return numero.toString().chars().distinct().count() == 1;
}

Traditional loop Nod digits

Or, if you prefer, a traditional algorithm:

boolean digitosIguais(Long numero) {
    char[] digitos = numero.toString().toCharArray();
    for (int i = 1; i < digitos.length; i++) {
        if (digitos[0] != digitos[i]) return false;
    }
    return true;
}

Sequences of predefined digits

Another idea would be to compare the number with a predefined sequence:

String[] repeticoes = {
    "11111111111111111111", 
    "22222222222222222222", 
    ..., 
    "99999999999999999999"
};

boolean digitosIguais(Long numero) {
    if (numero <= 0l) return false;
    String s = numero.toString();
    String repeticao = repeticoes[Integer.parseInt(numero.charAt(0))];
    return s.equals(repeticoes.substring(0, numero.length()));
}

Pre-calculation of possible combinations

Or even calculate the possible combinations and then identify if the number is in this set, which results in a virtually constant search time:

Set<Long> repeticoes = new HashSet<>();
for (long i = 1L; i <= 9L; i++) {
    for (long j = i; j > 0 && j < 1000000000000000000L; j = j * 10L + i ) {
        repeticoes.add(j);
    }
}

boolean digitosIguais(Long numero) {
    return repeticoes.contains(numero);
}

The above code results in a set of 162 numbers.

18

  • Algorithms implemented using Javascript.


    Algorithm #1

    Function digitsIguais(value) { value = value.toString();

    is (i = 1; i < value.length; i++) if (value[0] != value[i]) Return false;

    Return true; } Explanation:

    1. Converts the value to the String type (valor.toString())
    2. Loop starts at second position (i = 1) the condition being the size of the string (valor.length)
    3. If the first value is different from the iteration item (valor[0] != valor[i]), returns false (not equal) and exits the function
    4. If not: return true (equal)

Functional example: Jsfiddle


Algorithm #2

function digitosIguais2(sequencia){
    sequencia = sequencia.toString();

    for (i = 0; i < sequencia.length - 1; i++)
        if (sequencia.charAt(i) != sequencia.charAt(i + 1))
            return false;

    return true;
}
  1. Converts the value to the String type (sequencia.toString())
  2. Loop with string size condition less 1 (sequencia.length - 1)
  3. If the next position is different from the current one (sequencia.charAt(i) != sequencia.charAt(i + 1)) returns false (not equal).
    • Observing: I used the method charAt which returns the value of a position of an array.
  4. If not: return true (equal).

Functional example: Jsfiddle

14

Using C#, you can also use the operators bitwise, making a binary comparison:

public bool TodosIguais( int original ) {
  var deveSer = int.Parse(new string(original.ToString()[0], original.ToString().Length));
  return ( deveSer | original ) == original;
}

11

I do not know if you only wanted if the numbers were equal, so I dared and also made a palindrome :D

Jeez excuse, the Palindrome is following, the palindrome is a word (in the context I used number) reading from left to right, and from right to left has the same meaning (example, "we are", "bone"). Then in the isPalindromo I took the parameter and passed to a String and then I made a for of the size of String up to zero, to pick up the word and move on to another String, only that it reversed. And in the end I see if it is equal, that it came by the parameter and that I reversed.

And the isNumero I just took the first number and saw in the following numbers if there is one that is different. Because if it is different, it is no longer the same and I can give a break out of the loop.

public class Teste2 {

    public static void main(String[] args) {
        System.out.println(isPalindromo(3334333));
        System.out.println(isNumero(333333));
    }

    public static boolean isNumero(Integer valor) {
        boolean retorno = true;

        String numero = String.valueOf(valor);

         char elemento = numero.charAt(0);

        for(int i = 0;i < numero.length();i++){

            if(numero.charAt(i) != elemento){
                retorno = false;

            }
        }

        return retorno;
    }

    public static boolean isPalindromo(Integer valor) {
        boolean retorno = false;

        String numero = String.valueOf(valor);

        String numeroInvertido = "";

        for(int i = numero.length() - 1; i >= 0;i--){
            numeroInvertido += numero.charAt(i);
        }

        if(numero.equals(numeroInvertido)){
            retorno = true;
        }

        return retorno;
    }
}
  • It would be nice if you explained your logic to OP.

  • What is the purpose of isPalindromo?

  • Jeez excuse, the Palindrome is following, the Palindrome is a word (in the context I used number) reading from left to right, and from right to left has the same example meaning "we are","bone". Then in isPalindromo I took the parameter and passed to a String and then I did a String to zero size, to pick up the word and pass to another String only it reversed. And in the end I see if it’s the same, the one that came by the parameter and the one that I reversed.

  • And the isNumero I just took the first number and saw the following numbers there is one that is different, because if it’s different it’s no longer the same and I can break out of the loop.

  • 1

    I know what a palindrome, I’m just asking why was it that you added this in your reply.

  • 3

    It is not enough to be a number and palindrome for all digits to be equal. For example, 1001 is palindromic but does not answer to what was asked.

  • 1

    @kcpo I even think it’s nice your initiative to share a code with us, but it’s good to at least explain right at the beginning of the text that it’s just a complement, and that’s not the answer to what was asked. This can avoid confusion for future site visitors. Ideally stick to what has been asked,.

Show 2 more comments

6

Contribute my version in Haskell:

digitosSaoIguais :: Int -> Bool
digitosSaoIguais x = and $ map (== head xs) (tail xs)
    where xs = show x
  • show converts the number x to String (Char list).

  • now xs is a list of Char, i.e. 546 flipped ['5','4','6'].

  • map (== head xs) (tail xs) compares each element of tail xs with the first element of the list (head xs), e. g. ['5' == '4','5' == '6'].

  • and returns True if all elements of tail xs are equal to the first element of the list.

4

The first thing I thought was to do for potency, however no answer did it :

 

function checkEqual(num){
    var len = num.toString().length;            // VERIFICA QUANTOS CARACTERES ESTAO ENVOLVIDOS
    if(len == 1) return false;                  // SE COMPOSTO POR 1 NUMERO NAO GERA ERRO
    var n = parseInt(num.toString()[0]);        // PRIMEIRO NUMERO
    var r = Math.pow(n, len);                   // RESULTADO DA POTECIA DO PRIMEIRO NUMERO PELO TAMANHO
    var s = 1;
    for(var i = 0; i < len; i++){               // REALIZA A MULTIPLICACAO DE CADA ELEMENTO VINCULADO
        s *= parseInt(num.toString()[i]) || 0;  // SE ALGUM ELEMENTO NAO FOR NUMERICO MULTIPLICA POR 0
    }

    return r == s;                              // SE POTENCIA IGUAL AO RESULTADO DA MULTIPLICACAO
                                                // ENTAO SAO TODOS IGUAIS
}

function writeln(str){
    document.writeln(str+"<br/>");
}

writeln(checkEqual(555));
writeln(checkEqual(565));
writeln(checkEqual(5));
writeln(checkEqual(78));
writeln(checkEqual(11));

OBS

I would adopt the REGEX (\d)\1+.

  • Your solution is not always correct: checkEqual(214); returns true, because 2³ = 8 and 2 * 1 * 4 = 8 also :)

  • @tayllan indeed. I didn’t think of low numbers :/

2

A PHP response, useful to check that Cpf contains all the same numbers

$digitos = 11111111111;
$todosIguais = true;
foreach(str_split($digitos) as $num){
    foreach(str_split($digitos) as $num2){
        if($num != $num2){
            $todosIguais = false;
            break;
        }
    }
    if(!$todosIguais) break;
}
if($todosIguais) return false;

2

You could do it this way using recursion:

Example in Java:

public static boolean allDigitsEqual(int x) {
    String xStr = Integer.toString(x);
    if (xStr.substring(0, 1).equals(xStr.substring(1, 2))) {
        return xStr.substring(1).length() == 1 ? true : allDigitsEqual(Integer.parseInt(xStr.substring(1)));            
    } else {
        return false;
    } 
}

Example in PHP:

function allDigitsEqual($x) {
    $xStr = (string) $x;
    if (substr($xStr, 0, 1) == substr($xStr, 1, 1)) {
        return strlen(substr($xStr, 1)) == 1 ? true : allDigitsEqual(substr($xStr, 1));
    } else {
        return false;
    }
}

Example in C#:

public static bool allDigitsEqual(int x)
{
    String xStr = x.ToString();
    if (xStr.Substring(0, 1) == xStr.Substring(1, 1))
    {
        return xStr.Substring(1).Length == 1 ? true : allDigitsEqual(Int32.Parse(xStr.Substring(1)));
    }
    else
    {
        return false;
    }
}

0

Whereas the argument received by the function will be of the numeric type, you can do one like this:

  • script cast to string;
  • a loop of repetition (loop) of 0 to 9;
  • every time:
    • fill a string (pad) empty: '' up to the length of the argument with the repetition control number;
    • compares the string of pad with the argument cast and returns true if they are equal;
  • otherwise, when exiting the loop the function returns false;

Practical example, in Javascript:

(already with error handling)

function digitosIguais(num) {
    if (typeof num != 'number')
        throw 'digitosIguais espera um argumento tipo número!';

    if (num.toString().length <= 1)
        return false;

    for (let iguais, i = 0; i < 9; i++) {
        iguais = ('').padStart(num.toString().length, i);
        if (num == iguais)
            return true;
    }
    return false;
}

console.log(digitosIguais(122223456)); // false
console.log(digitosIguais(1111111111)); // true
console.log(digitosIguais(0)); // false
console.log(digitosIguais(1)); // false
console.log(digitosIguais(01)); // false
console.log(digitosIguais('12')); // erro

The interesting thing is that this theory, although simple, is compatible with the main languages.

And, depending on the case, you can use only the piece of the loop of repetition in its functions, such as CPF validation, CNPJ and the like.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.