NumberUtils { public static int atoi(String s) { if (s == null) { throw new NullPointerException("You passed a null string."); } if (s.length() == 0) { throw new NumberFormatException("The number string is empty."); } boolean isNegative = false; int startIndex = 0; if (s.charAt(0) == '+' || s.charAt(0) == '-') { startIndex = 1; if (s.charAt(0) == '-') { isNegative = true; } if (s.length() == 1) { throw new NumberFormatException(String.format( "The input string: %s is not a valid integer.", s)); } } long num = 0L; for (int index = startIndex; index < s.length(); index++) { char c = s.charAt(index); if (c < '0' || c > '9') { throw new NumberFormatException(String.format( "The input string: %s is not a valid integer.", s)); } num = num * 10 + (c - '0'); if (num > Integer.MAX_VALUE && !(isNegative && num == Integer.MAX_VALUE + 1)) { throw new NumberFormatException( String.format( "The input string: %s is not a valid integer as it overflows the integer range.", s)); } } int intNum = (int) num; return isNegative ? intNum * -1 : intNum; }  static int atoi(String s); static String itoa(int number); static int length(int number); static int reverse(int x); static boolean isValidInteger(String str);  }
@Test public void testAtoi_EmptyString() { boolean thrown = false; try { com.github.kowshik.bigo.common.NumberUtils.atoi(""); } catch (NumberFormatException e) { thrown = true; } assertTrue(thrown); }
@Test public void testAtoi_MalformedNumberSign() { boolean thrown = false; try { com.github.kowshik.bigo.common.NumberUtils.atoi("*"); } catch (NumberFormatException e) { thrown = true; } assertTrue(thrown); }
@Test public void testAtoi_MalformedNumberWithSign() { boolean thrown = false; try { com.github.kowshik.bigo.common.NumberUtils.atoi("+12.3"); } catch (NumberFormatException e) { thrown = true; } assertTrue(thrown); }
@Test public void testAtoi_MalformedNumberWithoutSign() { boolean thrown = false; try { com.github.kowshik.bigo.common.NumberUtils.atoi("12.3"); } catch (NumberFormatException e) { thrown = true; } assertTrue(thrown); }
@Test public void testAtoi_NumberWithPositiveSign() { assertEquals(123, com.github.kowshik.bigo.common.NumberUtils.atoi("+123")); }
@Test public void testAtoi_NumberWithNegativeSign() { assertEquals(-123, com.github.kowshik.bigo.common.NumberUtils.atoi("-123")); }
@Test public void testAtoi_NumberWithoutSign() { assertEquals(123, com.github.kowshik.bigo.common.NumberUtils.atoi("123")); }
@Test public void testAtoi_NumberOnlyWithSign() { boolean thrown = false; try { com.github.kowshik.bigo.common.NumberUtils.atoi("+"); } catch (NumberFormatException e) { thrown = true; } assertTrue(thrown); }