878909. Count Digits
Count Digits
Slug: count-digits-1606889545--123832 Difficulty: Easy Id: 878909 Topic Tags: CPP, Java
Summary
The Count Digits problem requires you to write a program that takes an integer as input and returns the number of digits in that integer. This problem involves basic arithmetic operations and is a great exercise in understanding how to manipulate integers.
Detailed Explanation
To solve this problem, we can use a simple algorithm that iterates through the integer until it reaches zero. In each iteration, we can increment a counter variable for each digit present in the number. We can achieve this by using the modulo operator (%) to get the remainder of the division of the number by 10. This will give us the last digit of the number.
Here is a step-by-step breakdown of the solution:
- Initialize a variable
countto 0, which will store the total count of digits. - While the input integer is greater than 0:
- Get the last digit of the number by using the modulo operator (
%) with 10 as the divisor. - Increment the
countvariable by 1 for each non-zero digit found. - Update the number by performing integer division by 10 to move to the next digit.
- Get the last digit of the number by using the modulo operator (
- Return the total count of digits.
Time complexity: O(log n), where n is the input integer, because we are essentially dividing the number by 10 in each iteration until it reaches zero.
Space complexity: O(1), as we only use a constant amount of space to store the count variable.
Optimized Solutions
Java
public class Main {
public static int countDigits(int n) {
int count = 0;
while (n > 0) {
n /= 10;
if (n != 0) {
count++;
}
}
return count;
}
public static void main(String[] args) {
System.out.println(countDigits(123)); // Output: 3
}
}