FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/Maths/NumberOfDigits.java at master · loisoft/Java · GitHub
loisoft
/
Java
Public
forked from
TheAlgorithms/Java
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
Maths
/
NumberOfDigits.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
59 lines (54 loc) · 1.65 KB
Breadcrumbs
Java
/
Maths
/
NumberOfDigits.java
Copy path
File metadata and controls
59 lines (54 loc) · 1.65 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
55
56
57
58
59
package
Maths
;
/** Find the number of digits in a number. */
public
class
NumberOfDigits
{
public
static
void
main
(
String
[]
args
) {
int
[]
numbers
= {
0
,
12
,
123
,
1234
, -
12345
,
123456
,
1234567
,
12345678
,
123456789
};
for
(
int
i
=
0
;
i
<
numbers
.
length
; ++
i
) {
assert
numberOfDigits
(
numbers
[
i
]) ==
i
+
1
;
assert
numberOfDigitsFast
(
numbers
[
i
]) ==
i
+
1
;
assert
numberOfDigitsFaster
(
numbers
[
i
]) ==
i
+
1
;
assert
numberOfDigitsRecursion
(
numbers
[
i
]) ==
i
+
1
;
}
}
/**
* Find the number of digits in a number.
*
* @param number number to find
* @return number of digits of given number
*/
private
static
int
numberOfDigits
(
int
number
) {
int
digits
=
0
;
do
{
digits
++;
number
/=
10
;
}
while
(
number
!=
0
);
return
digits
;
}
/**
* Find the number of digits in a number fast version.
*
* @param number number to find
* @return number of digits of given number
*/
private
static
int
numberOfDigitsFast
(
int
number
) {
return
number
==
0
?
1
: (
int
)
Math
.
floor
(
Math
.
log10
(
Math
.
abs
(
number
)) +
1
);
}
/**
* Find the number of digits in a number faster version.
*
* @param number number to find
* @return number of digits of given number
*/
private
static
int
numberOfDigitsFaster
(
int
number
) {
return
number
<
0
? (-
number
+
""
).
length
() : (
number
+
""
).
length
();
}
/**
* Find the number of digits in a number using recursion.
*
* @param number number to find
* @return number of digits of given number
*/
private
static
int
numberOfDigitsRecursion
(
int
number
) {
return
number
/
10
==
0
?
1
:
1
+
numberOfDigitsRecursion
(
number
/
10
);
}
}
Back
|
FazBrowse Home
|
New Git URL