Skip to content

Instantly share code, notes, and snippets.

@sopherwang
Created September 14, 2014 22:10

Revisions

  1. sopherwang created this gist Sep 14, 2014.
    46 changes: 46 additions & 0 deletions gistfile1.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    public int atoi(String str) {
    //1. space
    //2. +/-
    //3. invalid character
    //4. null
    //5. MAX_INT and MIN_INT

    if (str == null || str.length() == 0)
    return 0;

    str = str.trim();
    char flag = '+';
    int i = 0;

    if (str.charAt(i) == '-')
    {
    flag = '-';
    i++;
    }
    else if (str.charAt(i) == '+')
    i++;

    double result = 0;
    while (i < str.length() && str.charAt(i) <= '9' && str.charAt(i) >= '0')
    {
    result = result * 10 + (str.charAt(i) - '0');
    i++;
    }

    if (flag == '-')
    {
    result = -result;
    }

    if (result > Integer.MAX_VALUE)
    {
    return Integer.MAX_VALUE;
    }

    if (result < Integer.MIN_VALUE)
    {
    return Integer.MIN_VALUE;
    }

    return (int) result;
    }