Given a number, get the digit of tens

Asked

Viewed 315 times

1

Write a function that takes an integer number of up to three digits and returns to dozens quantity of that number. Do not make type transformations.

  • Input: (2) Output: 0
  • Input: (85) Output: 8
  • Input: (321) Output: 2

Code:

def questao6(n):
    result = n // 10
    print(result)

In case 3, the code returns me 32 and not 2. There is how I solve this issue without using anything but operators?

2 answers

2


With 321, the result is 32 because you only divide the number by 10 - and the operator // makes the "entire division", that is, round the result. And 321 divided by 10 gives 32.

What’s left is to get the last digit of the split result, which you can get by using the rest of the division by 10 (with the operator %):

def questao6(n):
    result = (n // 10) % 10
    print(result)

Although, if it’s just for printing, you don’t even need the variable result:

def questao6(n):
    print((n // 10) % 10)

But I would make the function return the value, and then who called it decides what to do (and even print):

def dezena(n): # dando um nome melhor para a função
    return (n // 10) % 10

for i in [2, 85, 321]: # testando com vários números
    print(i, dezena(i))

And just to be pedantic, what’s being asked for is actually the digit corresponding to ten. Because if it were really the "amount of tens", then 32 would be right, after all 321 "has" indeed 32 tens :-)

  • thank you very much!! I am restricted to do only with operators.

-2

 def questao6(n):
     result = ( n % 100 ) // 10
     print(result)
  • You will only get the value of ten.

Browser other questions tagged

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