Java Solution with Unit Tests


  • 0
    S

    Here is a very simple straight-forward solution:

    public class Solution {
    
        public int myAtoi(String str) {
            String pre = null;
            try {
                char[] in = str.trim().toCharArray();
    
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < in.length; i++) {
                    if (Character.isDigit(in[i])) {
                        sb.append(in[i]);
                    } else if (i == 0) {
                        if (in[i] == '+' || in[i] == '-') {
                            sb.append(in[i]);
                        } else {
                            break;
                        }
                    } else {
                        break;
                    }
                }
                pre = sb.toString();
                return Integer.parseInt(sb.toString());
            } catch (NumberFormatException e) {
                if (pre == null || pre.isEmpty() || pre.length() == 1) {
                    return 0;
                } else if (pre.startsWith("-")) {
                    return Integer.MIN_VALUE;
                } else {
                    return Integer.MAX_VALUE;
                }
            }
        }
    }
    

    And here are some unit tests for this solution:

    import org.junit.Assert;
    import org.junit.Test;
    
    public class SolutionTest {
        @Test
        public void test1() {
            int actual = new Solution().myAtoi(" b11228552307");
            Assert.assertEquals(0, actual);
        }
    
        @Test
        public void test2() {
            int actual = new Solution().myAtoi("-");
            Assert.assertEquals(0, actual);
        }
    
        @Test
        public void test3() {
            int actual = new Solution().myAtoi("+");
            Assert.assertEquals(0, actual);
        }
    
        @Test
        public void test4() {
            int actual = new Solution().myAtoi("-2147483649");
            Assert.assertEquals(Integer.MIN_VALUE, actual);
        }
    
        @Test
        public void test5() {
            int actual = new Solution().myAtoi("2147483649");
            Assert.assertEquals(Integer.MAX_VALUE, actual);
        }
    
        @Test
        public void test6() {
            int actual = new Solution().myAtoi("  -0012a42");
            Assert.assertEquals(-12, actual);
        }
    
        @Test
        public void test7() {
            int actual = new Solution().myAtoi("");
            Assert.assertEquals(0, actual);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.