Java code:
class atoi
{
public static int atoi(String str)
throws NumberFormatException
{
if (str == null) throw new NumberFormatException("null");
if (str == "-2147483648") return Integer.MIN_VALUE;
int retVal = 0;
int i = 0;
char[] s = str.toCharArray();
boolean isNegative = s[0] == '-';
if (isNegative) i++;
if ((isNegative && str.length() > 11) || (!isNegative && str.length() > 10))
throw new NumberFormatException(str);
while (i < s.length)
{
retVal *= 10;
if (s[i] > '9' || s[i] < '0')
throw new NumberFormatException(str);
retVal += s[i++] - '0';
if (retVal < 0)
throw new NumberFormatException(str);
}
if (isNegative)
retVal *= -1;
return retVal;
}
public static void main(String[] args)
{
String s = null;
System.out.println("atoi="+atoi(s));
System.out.println("max="+Integer.MAX_VALUE);
System.out.println("min="+Integer.MIN_VALUE);
System.out.println("parseInt="+Integer.parseInt(s));
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment