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

Asked

Viewed 1,739 times

11

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

Test cases:

  • 123000 zero numbers 3
  • 102030 zero numbers 1

Open to suggestions!

  • Want answer in all these languages?

  • 3

    Choose the language better or it will complicate it. Each one has a different way.

  • Yes.. It will be very interesting to have several answers!

  • May initially be the language C.

  • But it makes the question too broad. Perhaps focusing on doubt one language at a time is more interesting.

  • 2

    I think this sort of thing goes better with the Rosetta Code, but if anyone ventures to answer, I’m good. Everyone can post in the language they know.

  • Ready changed to C or JAVA language. Any response ?

  • How to use resettacode.org ?

  • @alexjosesilva just commented as an example

  • 1

    @Bacco, as I did an answer in Groovy, do you think it prudent to put the Grooyv tag on the question?

  • 1

    @Cantoni I think you can start the answer by saying "Just to complement, as the original question asked in several languages, follows a version in Groovy". I think it’s better than we tag it. UPDATE: Now that I’ve seen that you’ve done just that. I think that’s enough.

Show 6 more comments

10 answers

16


Would this be:

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

In C: See working in the ideone. And in the repl it.. Also put on the Github for future reference.

In Java: See working in the ideone. And in the repl it.. Also put on the Github for future reference.

Obviously it can be improved, as for example it can validate the input of function data. I wanted to keep it simple since the question doesn’t say anything about this and it can be an exercise for the AP.

  • great...solved the problem perfectly. Congratulations!

  • @alexjosesilva Just a warning: pass 0 for the method will result in a division error. This is not strictly necessary for logic, but I’ve seen teachers discount grades for that detail. Even they like to "pick up" students during work presentations asking to type negative values and zeroes just to see what happens. I myself am guilty of this. D

  • Um...pertinent comment @utluiz

11

In the comments of the question it was suggested that the answer be given in any language. So to add an example at 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 need to test if the number is == 0, if it is, it is necessary to return 0 and not 1 (as in the original version). For this, a se ternary is made.

If it differs from 0, then the number is converted to String. Then the string is reversed. A closure takeWhile assembles a list where each element will be a '0'. To takeWhile will abort when the first character that is not a zero is found. Finally, the method is called size() to count how many elements the list has (i.e., how many zeros have been found on the right).

See working on Ideone

You can even inject a method called contaZerosDireita in the Integer or Long class, see how:

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

To use simply do this:

def numero = 2220002330000000
println numero.contaZerosDireita()

or directly

println 2220002330000000.contaZerosDireita()
  • 1

    I’m happy with your initiative @Cantoni...

  • Thanks, @alexjosesilva. The goal of my reply is just to present a different shape in Groovy. By explaining the code I can get a little bit past the language features (like Closures, for example).

  • Pass only 0 will return 1, right? I think you need an extra test.

  • Thanks @utluiz, corrected version from your remark.

8

Java version

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

Code in 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 split in a tuple

Code in Ideone

Version in Clojure

(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: declares a function
  • Line 2: parameter np
  • Line 3: declares a loop with two parameters:
    1. z with the initial value 0
    2. n with the initial value of np
  • Line 4: checks the number n is less than 10 or if the rest of the division is non-zero
    • Line 5: if the above test is true, it returns z
    • Line 6: runs if the above test is false and as loops in Lisp-based languages are made using recursion, then it basically uses the recur to return to the beginning of the incrementing loop z and dividing n for 10.

Code in Ideone

8

Version in Haskell :)

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 the list of Int (so that the original number 120 turns [0,2,1]).

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

  • length returns the size of the list that contains only 0.

  • 5

    :[] -- POS: programming oriented to Miles. D

  • /\ HHAHAAH, boaa @utluiz

  • 1

    hahah, programming didn’t even notice. Haskell == Smiles!

5

loop{
  divide por 10 e soma 1 no contador se n%10 == 0
}

2

PHP version

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

Version in C#

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

C# Ideone

Just for the record :)

2

Javascript version (ES6) with Regexp:

const contarZeros = (numero) => /0*$/.exec(numero)[0].length;
  • Gabriel, Cool! (+1)

  • 1

    @Jjoao thanks, I edited, I found a better way ;)

1

Version in pseudocode:

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 trace numbers like 000 for 0.

1

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

Version Perl 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)' 

Version Perl 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 to say:

  • field separator is anything but zero awk -F'[^0]'
  • for each line, print the length of the last field length($NF)

0

Version in Python 3

def end_zeros(num: int) -> int:
   count = 0
   while num % 10 == 0:
      count += 1
      num /=  10
      if num == 0:
         count = 1
         return count
   return count

Browser other questions tagged

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