patternjavaMinor
Parsing a long without using inbuilt function parseLong
Viewed 0 times
parselongwithoutlongfunctionparsingusinginbuilt
Problem
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'9')
{
throw new NumberFormatException();
}
return value-'0';
}Solution
If the condition
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:
Also in your
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.
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.
Code Snippets
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));
}
}public int getValue(char ch){
if (Character.isDigit(ch)){
return ch - 48;
} else {
throw new NumberFormatException();
}
}Context
StackExchange Code Review Q#79371, answer score: 3
Revisions (0)
No revisions yet.