Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert string to number without using library function [closed]

Tags:

java

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()
like image 530
Basit Avatar asked Sep 24 '12 12:09

Basit


1 Answers

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.

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

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
like image 94
Bohemian Avatar answered Sep 18 '22 14:09

Bohemian