implement atoi function in java

122 Views Asked by At

I am trying to implement the Atoi function in java, but it is showing me the error as:

java.lang.NumberFormatException: For input string: 
at line 67, java.base/java.lang.NumberFormatException.forInputString
at line 721, java.base/java.lang.Long.parseLong
at line 836, java.base/java.lang.Long.parseLong
at line 26, Solution.myAtoi
at line 54, __DriverSolution__.__helper__
at line 84, __Driver__.main

The code I implemented is as below :

class Solution {
  
  public int myAtoi(String s) {
    String ans = "";
    int i = 0;
    int j = 0;
    int sign = 0;
    while (i < s.length() - 1) {
      if (s.charAt(i) == 0) {
        j++;
      }
      i++;
    }
    if (s.charAt(i) == 45) {
      sign = -1;
    } else {
      sign = +1;
    }
    i++;
    j++;
    while (i < s.length() - 1) {
      if (s.charAt(i) >= 48 && s.charAt(i) <= 57) {
        ans = ans + s.charAt(i);
      }
    }
    long x = Long.parseLong(ans);
    if (sign == (-1)) {
      x = x * (-1);
    }
    int ret = (int) x;
    return ret;
  }
}

Can anyone point out the error in the code?

0

There are 0 best solutions below