3
\$\begingroup\$

I came across it as a problem to solve. What kind of limitations are there?

public long parseLong(String number)
{
    long n=0;
    if(number==null || number.isEmpty())
    {
        System.out.println("Number is null or empty");
        return n;
    }
    boolean isNegative = false;
    if(number.charAt(0)=='-')
    {
        isNegative=true;
    }
    else {
        n = getValue(number.charAt(0));
    }
    for(int i=1;i<number.length();i++)
    {
        n = n*10 + getValue(number.charAt(i));
    }
    return isNegative ? (-1*n) : n;
}
public int getValue(char ch)
{
    int value = ch;
    if(value<'0' || value>'9')
    {
        throw new NumberFormatException();
    }
    return value-'0';
}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

If the condition if(number==null || number.isEmpty()) holds true the method should throw a ParseException rather than incorrectly returning 0.

Also your logic for non-negative numbers isn't quite correct, as you are ignoring the first character if the length of the input is > 1. To fix this you should include charAt(0) in your else statement as follows:

    if(number.charAt(0)=='-'){
        isNegative=true;
    }
    else {
        n = getValue(number.charAt(0));

        for(int i=1;i<number.length();i++){
            n = n*10 + getValue(number.charAt(i));
        }
    }

Also in your getValue method your check, whether the character is a digit can be simplified:

public int getValue(char ch){
    if (Character.isDigit(ch)){
        return ch - 48;
    } else {
        throw new NumberFormatException();
    }
}

These are local optimizations. I would consider converting the string to an array of integers first (and by doing that determine, whether the string is valid in the first place) and then compute the value. By doing the computations as you go you are risking doing them in vain if a later input character is not a digit.

One thing that is missing in your code is considering the maximum value for a long and checking for violations.

\$\endgroup\$
2
  • \$\begingroup\$ Thanks a lot @barq. I did not understand why the logic will be incorrect for non-negative input of length greater than 1. Can you please provide any example because I have tested the code and it was working fine for me. About checking for range of long, should I store the long in long long and check every time if it exceeds the range ? \$\endgroup\$ Commented Feb 2, 2015 at 19:55
  • \$\begingroup\$ I would recommend writing some tests to assert a range of cases and identify where it goes wrong. \$\endgroup\$
    – barq
    Commented Feb 2, 2015 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.