Tutte le sfide
Facile 0 risolte 0% di accettazione

Count Digits

Count the decimal digits of a positive integer.

Cosa imparerai

  • Count how many times a number can be divided by 10
  • Use a counter inside a while loop
  • Treat single-digit numbers as an edge case

Problema

Mostra traduzione

Count how many decimal digits n has when written normally, without leading zeros.

Implement count_digits(n).

Input

n: A positive integer.

Output

Return the number of digits.

Vincoli

1 ≤ n ≤ 10¹⁸

Esempi

Esempio 1
Input:
n = 352

Output atteso:
expected = 3
Input:
long long n = 352;

Output atteso:
long long expected = 3;
Input:
long n = 352;

Output atteso:
long expected = 3;

Spiegazione

352 has three digits.

Esempio 2
Input:
n = 7

Output atteso:
expected = 1
Input:
long long n = 7;

Output atteso:
long long expected = 1;
Input:
long n = 7;

Output atteso:
long expected = 1;

Spiegazione

A single digit.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

You only need to know how many times you can remove a digit before nothing remains.

Suggerimento 2

A loop with division by 10 or a string length both work well.

Suggerimento 3

Don’t forget that any positive single-digit number still has exactly one digit.

Complessità attesa

O(d) time, O(1) extra space

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.