Suppose i want to create a method that takes a number as a string and return its number form. Like
getNumber("123456");
public int getNumber(String number) {
//No library function should used. Means i can't do Integer.parseInteger(number).
} //end of getNumber()
How can i implement that method like
public int getNumber(String number) {
for (int i=0; i<number.length; i++) {
char c = number.getCharacter(i);
///How can i proceed further
} //end of for()
} //end of getNumber()
Without using a library function, subtract the character '0'
from each numeric character to give you its int
value, then build up the number by multiplying the current sum by 10 before adding the next digit's ìnt
value.
public static int getNumber(String number) {
int result = 0;
for (int i = 0; i < number.length(); i++) {
result = result * 10 + number.charAt(i) - '0';
}
return result;
}
public static int getNumber(String number) {
return number.chars().reduce(0, (a, b) -> 10 * a + b - '0');
}
This works primarily because the characters 0-9
have consecutive ascii values, so subtracting '0'
from any of them gives you the offset from the character '0'
, which is of course the numeric equivalent of the character.
Disclaimer: This code does not handle negative numbers, arithmetic overflow or bad input.
You may want to enhance the code to cater for these. Implementing such functionality will be instructive, especially given this is obviously homework.
Here's some test code:
public static void main(String[] args) {
System.out.println(getNumber("12345"));
}
Output:
12345
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With