# Determine if all digits are equal

33

Parameterized by a numeric value. For example, 888 or 546. And I have a function that returns a boolean `true` value if all numbers are equal or `false` if they are different.

How do I proceed with the algorithm?

asked by anonymous 23.10.2015 / 00:45

28

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 response, 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."); }
``````

23.10.2015 / 01:31
29
• Get the number of decimal places of a given original O number using the formula `Floor(Log10(numero)) + 1`

Example:

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

Example:

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

Example:

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

23.10.2015 / 01:09
25
• Let X be the original number.
• Divide X by 10 and get the rest, call it R1.
• Repeat while X is non-zero
• 3.1 Give R2 the rest of the division of X by 10.
• 3.2 If R1 is other than R2, return false.
• 3.2 Assign to X the quotient of the entire division of X by 10.
• Return true.

Note that this approach works only using math, 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 the blue button ► Run above to test and note the result.

23.10.2015 / 01:21
25

Playing the charades 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)*\$/'
``````

2) an algorithm:

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

23.10.2015 / 02:24
21

Javascript implementation of the provided formula in JJoao's answer .

It 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 the blue button ► Run above to test and note the result.

13.04.2017 / 14:59
20

# With regular expressions

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

### Explaining

`^` frame the beginning of the string

`(\d)` get a numeric digit

the next character is equal to the digit I got

`*` this character can be repeated several times, or none

% frame_with% end of string (as I'm marking the beginning and ending, I guarantee there will be no extra characters in the string)

# Implementing in javascript

### I made a function to make it easier to use

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

### Explaining

`\$` is to transform the result into boolean

`!!` is to convert the number to string, before applying the regular expression

### Tests

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

30.10.2015 / 14:20
19

# Java 8 with chars stream

In Java 8, it's easy with streams :

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

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;
}
``````

# Predefined digit sequences

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 that set, which results in a practically 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 ) {
}
}

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

The code above results in a set of 162 numbers.

27.10.2015 / 05:33
18
• Algorithms implemented using Javascript.

Algorithm # 1

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

for (i = 1; i

23.10.2015 / 01:19
14

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

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

23.10.2015 / 02:46
11

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

I'm sorry, the Palindrome is next, the palindrome is a word (in the context I used number) that reading from left to right, and from right to left has the same meaning (example, "we are", "bone" ). Then in%% I got the parameter and I went to a `isPalindromo` and then I made a `String` of the size of `for` to zero, to get the word and move to another `String` , only it inverted. And in the end I see if it's the same, the one that came by the parameter and the one I invested.

And the `String` I just got the first number and saw in the next numbers if there is any one that is different. Because if it is different, it is no longer the same and I can give `isNumero` to get 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;
}
}
``````

23.10.2015 / 01:26
6

``````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` become `['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.

05.03.2016 / 00:24
4

The first thing he thought was doing by power, yet no answer did so:

``````

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 REGEX `(\d)+` .

05.03.2016 / 01:34
2

A PHP response, useful for checking that the cpf contains all equal 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;
``````

13.11.2015 / 19:58
2

You could do this using recursion:

Java example:

``````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;
}
}
``````

C # example:

``````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;
}
}
``````

13.11.2015 / 20:36