-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountDigitsInNumber.java
More file actions
54 lines (32 loc) · 1.06 KB
/
Copy pathCountDigitsInNumber.java
File metadata and controls
54 lines (32 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
Count the number of Digits
TC :- Olog10(n) where n is the number of digits bcz we we are dividing the number by 10 each time
*/
import java.io.*;
import java.util.*;
public class CountDigitsInNumber{
public static int findTheNumberOfDigitsInGivenNumber(int num){
int noOfDigits = 0;
while( num > 0 ){
//Removes the last digit in the number, quotient is assigned to num
num = num /10;
noOfDigits++;
}
//another one liner approach is noOfDigits = (int) Math.log10(num)+1;
return noOfDigits;
}
public static void main(String[] args){
int num = 5678;
int noOfDigits = findTheNumberOfDigitsInGivenNumber(num);
System.out.println("the no of digits for "+ num +" is:"+noOfDigits);
}
}
//o/p:- the no of digits for 5678 is:4
/* Recursiobn version
static int countDigit(long n)
{
if (n/10 == 0)
return 1;
return 1 + countDigit(n / 10);
}
*/