How to convert string to number without using library function

Suppose I want to create a method that takes a number as a string and returns its numeric form. how

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 this method, for example

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()
+5
source share
2 answers

Without using the library function, subtract the character '0'from each numeric character to give you a value int, and then create a number by multiplying the current amount by 10 before adding the next value ìnt.

Java 7

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;
}

Java 8

public static int getNumber(String number) {
    return number.chars().reduce(0, (a, b) -> 10 * a + b - '0');
}

, 0-9 ascii, '0' '0', , , .


: , .

, . , , , , .


:

public static void main(String[] args) {
    System.out.println(getNumber("12345"));
}

:

12345
+14

Integer.parseInt(str). Long, Short, Double .

-3

All Articles