Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitccf5065

Browse files
committed
Add HexadecimalToDecimal conversion
1 parentf82bf1a commitccf5065

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
packagecom.conversions;
2+
3+
4+
publicclassHexadecimalToDecimal {
5+
6+
/**
7+
* This method converts a Hexadecimal number to a decimal number
8+
*
9+
* @param hexadecimalStr
10+
* @return decimal number
11+
*/
12+
publicStringhexToDecimal(StringhexaStr) {
13+
StringhexaNumbers ="0123456789ABCDEF";
14+
intm,result =0;
15+
charletter;
16+
StringdecimalStr;
17+
hexaStr =hexaStr.toUpperCase();
18+
19+
for (inti =0 ;i <hexaStr.length() ;i++) {
20+
/**
21+
* Letter will store the hexadecimal number as long as we loop through
22+
* the string
23+
*/
24+
letter =hexaStr.charAt(i);
25+
26+
/**
27+
* m is the index of the number that we are looping through in the
28+
* hexaNumbers
29+
*/
30+
m =hexaNumbers.indexOf(letter);
31+
result =16*result +m;
32+
}
33+
34+
decimalStr =String.valueOf(result);
35+
returndecimalStr ;
36+
}
37+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
packagecom.conversions;
2+
3+
4+
importorg.junit.jupiter.api.Assertions;
5+
importorg.junit.jupiter.api.Test;
6+
7+
classHexadecimalToDecimalTest {
8+
9+
@Test
10+
voidtestHexadecimalToDecimalTest() {
11+
12+
HexadecimalToDecimalhexadecimalToDecimal =newHexadecimalToDecimal();
13+
Assertions.assertEquals("171",hexadecimalToDecimal.hexToDecimal("AB"),"Incorrect Conversion");
14+
Assertions.assertEquals("5680077",hexadecimalToDecimal.hexToDecimal("56ABCD"),"Incorrect Conversion");
15+
Assertions.assertEquals("5174921",hexadecimalToDecimal.hexToDecimal("4ef689"),"Incorrect Conversion");
16+
Assertions.assertEquals("1263",hexadecimalToDecimal.hexToDecimal("4EF"),"Incorrect Conversion");
17+
Assertions.assertEquals("11259375",hexadecimalToDecimal.hexToDecimal("ABCDEF"),"Incorrect Conversion");
18+
//It returns -1 if you enter a wrong hexaDecimal
19+
Assertions.assertEquals("-1",hexadecimalToDecimal.hexToDecimal("K"),"Incorrect Conversion");
20+
21+
}
22+
23+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp