How to count the zeros to the right of a number?

11

I have a number, nnnnn000 . I must count how many zeros on the right has this number.

Test Cases:

  • 123000 zeros numbers 3
  • 102030 zeros numbers 1

Open to suggestions!

    
asked by anonymous 12.02.2016 / 21:39

9 answers

16

It would be this:

int countZeros(int n) {
    int count = 0;
    while (n % 10 == 0) {
        count++;
        n /= 10;
    }
    return count;
}

See working on ideone in C and in Java a>.

Obviously it can be improved, as for example you can validate the data entry of the function. I preferred to leave it simple since the question does not say anything about it and can be an exercise for the AP.

    
12.02.2016 / 21:51
11

In the comments of the question it was suggested that the answer be given in any language. So to add I leave an example in Groovy :

Example with 7 zeros

def numero = 2220002330000000
assert numero==0?0:numero.toString().reverse().takeWhile{it=='0'}.size() == 7

Example with no zero

def numero = 222000233
assert numero==0?0:numero.toString().reverse().takeWhile{it=='0'}.size() == 0

Explaining the code:

First (as noted by @utluiz), you must test whether the number is == 0 , if so, you must return 0 instead of 1 (as in the original version). For this, a% ternary% is made.

If it is different from se , then the number is converted to String. Then the string is reversed. The closure 0 assembles a list where each element will be takeWhile . The '0' will stop when the first non-zero character is encountered. Finally, the takeWhile method is called to count how many elements the list has (that is, how many zeros were found on the right).

See working at Ideone

You can even inject a method called size() into the Integer or Long class, see how:

Long.metaClass.contaZerosDireita {
    return delegate==0?0:delegate.toString().reverse().takeWhile{it=='0'}.size()
}

To use just do this:

def numero = 2220002330000000
println numero.contaZerosDireita()

or directly

println 2220002330000000.contaZerosDireita()
    
12.02.2016 / 22:20
8

Java version

byte rightZeros(long n) {
    for (byte z = 0; ; z++, n /= 10) {
        if (n < 10 || n % 10 != 0) return z;
    }
}

Code on IdeOne

Python version

def right_zeros(n):
    z = 0
    while True:
        n, r = divmod(n, 10)
        if n == 0 or r != 0:
            return z
        z += 1

print(right_zeros(123000))
print(right_zeros(102030))
print(right_zeros(123123))

Considerations:

  • divmod returns both the result and the rest of the division in a tuple

Code on IdeOne

Clojure version

(defn right_zeros
  [np]
    (loop [z 0 n np]
        (if (or (< n 10) (not= (mod n 10) 0))
            z
            (recur (inc z) (/ n 10)))))

(println (right_zeros 123000))
(println (right_zeros 102030))
(println (right_zeros 123123))

Considerations:

  • Line 1: declare a function
  • Line 2: parameter np
  • Line 3: declares a loop with two parameters:
  • z with initial value 0
  • n with the initial value of np
  • Line 4: verifies that the number n is less than 10 or if the rest of the division is nonzero
    • Line 5: If the above test is true, it returns z
    • Line 6 executes if the above test is false and because loops in Lisp-based languages are done using recursion, then it basically uses recur to return to the beginning of the loop by incrementing z and dividing n by 10 .

Code on IdeOne

    
15.02.2016 / 02:05
8

Haskell Version:)

countZerosDireita :: Int -> Int
countZerosDireita = length . takeWhile (==0) . reverse . map (read . (:[])) . show
  • show converts the number to String (Char list).

  • map (read . (:[])) turns the String into an Int list.

  • reverse reverses Int list (so the original number 120 becomes [0.2,1]).

  • takeWhile (==0) takes all Int from the list as long as they are 0 .

  • length returns the size of the list containing only 0 .

25.02.2016 / 00:31
6
loop{
  divide por 10 e soma 1 no contador se n%10 == 0
}
    
12.02.2016 / 21:47
2

PHP version

function contarZeros($n) {
    $count = 0;
    while ($n % 10 == 0) {
        $count++;
        $n /= 10;
    }
    return $count;
}

C # version

public static int ContarZeros(int n) {
    int count = 0;
    while (n % 10 == 0) {
        count++;
        n /= 10;
    }
    return count;
}

C # Ideone

Just to include:)

    
08.03.2016 / 02:50
1

JavaScript Version (ES6) with RegExp:

const contarZeros = (numero) => /0*$/.exec(numero)[0].length;
    
19.04.2016 / 18:21
1

Pseudocode version:

function contar-zeros (numero conta)
    if numero = 0
        return 1
    else-if (mod numero 10) = 0
       contar-zeros (numero / 10), (conta + 1) //Recursiva
    else
       return conta

Version in Common Lisp for explanation:

(defun contar-zeros (num &optional (count 0))
   (cond ((= 0 num) 1) 
         ((= 0 (mod num 10)) (contar-zeros (/ num 10) (1+ count)))
         (t count)))

Most programming languages match numbers like 000 to 0 .

    
08.03.2016 / 02:26
0

Assuming entries to be one number per line, follow 4 solutions oneliners a little Machiavellian.

Perl Version 1

perl -nE '/\d(0*)\b/g and say length($1)'

Explanation

para cada linha ∈ texto                     ⎪    perl -n
 ⎧ procura zeros no final de uma palavra    ⎪      /\d(0*)\b/g
 ⎪                                          ⎪      and
 ⎩ escreve o comprimento da string match $1 ⎪      say length($1)' 

Perl Version 2, 3

perl -nE  'say log(s/\d*[1-9]/1/r)/log(10)'
perl -nlE 'say length( s/\d*[1-9]//r )'

Awk Version

awk -F'[^0]' '{print length($NF)}'

that is:

  • field separator is anything but zero awk -F'[^0]'
  • For each line, print the length of the last field length($NF)
19.04.2016 / 14:43