Skip to content

Commit 76ac7ce

Browse files
get first digit
1 parent fe71775 commit 76ac7ce

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.examplehub.maths;
2+
3+
public class GetTheFirstDigit {
4+
5+
/**
6+
* Get the first digit of a number.
7+
*
8+
* @param number the number to be checked.
9+
* @return the first digit of given number.
10+
*/
11+
public static int firstDigit(int number) {
12+
number = Math.abs(number);
13+
while (number >= 10) {
14+
number /= 10;
15+
}
16+
return number;
17+
}
18+
19+
/**
20+
* Get the first digit of a number using string.
21+
*
22+
* @param number the number to be checked.
23+
* @return the first digit of given number.
24+
*/
25+
public static int firstDigitByString(int number) {
26+
number = Math.abs(number);
27+
return Integer.parseInt(("" + number).substring(0, 1));
28+
}
29+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.examplehub.maths;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class GetTheFirstDigitTest {
8+
9+
@Test
10+
void test() {
11+
int[][] testNumbers = {{-123, 1}, {0, 0}, {123, 1}, {123456789, 1}};
12+
for (int[] testNumber : testNumbers) {
13+
assertEquals(testNumber[1], GetTheFirstDigit.firstDigit(testNumber[0]));
14+
assertEquals(testNumber[1], GetTheFirstDigit.firstDigitByString(testNumber[0]));
15+
}
16+
}
17+
}

0 commit comments

Comments
 (0)