Golang 3 steps


  • 0
    A

    还是不如C++写起来简单
    cant be simple as coding by C++

    func myAtoi(str string) int {
    	val := 0
    	flag := 1
    	strChars := []byte(str)
    	i := 0
    
    	// 1.
    	for ; i < len(strChars); i++ {
    		if strChars[i] != ' ' && strChars[i] != '\t' && strChars[i] != '\n' && strChars[i] != '\r' {
    			break
    		}
    	}
    
    	// 2.
    	if len(str) == 0 {
    		return 0
    	}
    	if strChars[i] == '-' {
    		flag = -1
    		i++
    	} else if strChars[i] == '+' {
    		i++
    	}
    
    	// 3.
    	for ; i < len(strChars) && '0' <= strChars[i] && strChars[i] <= '9'; i++ {
    		val = val*10 + int(strChars[i]-'0')
    		if flag*val > 2147483647 {
    			flag = 2147483647
    			val = 1
    		} else if flag*val < -2147483648 {
    			flag = -2147483648
    			val = 1
    		}
    	}
    	return flag * val
    }
    

Log in to reply
 

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