LintCode: String to Integer

String to Integer



Similar Problems:


Description
Given a string, convert it to an integer. You may assume the string is a valid integer number that can be presented by a signed 32bit integer (-2^31 ~ 2^31-1).

Example
Given “123”, return 123.

Github: code.dennyzhang.com]]

Credits To: lintcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// Blog link: https://code.dennyzhang.com/string-to-integer
// Basic Ideas:
// Complexity: Time O(1), Space O(1)
/**
 * @param str: A string
 * @return: An integer
 */
func stringToInteger (str string) int {
    res := 0
    negative := false
    for i, ch := range str {
        if i == 0 && ch == '-' {
            negative = true
            continue
        }
        res = res*10 + int(ch-'0')
    }
    if negative { res = -res }
    return res
}
linkedin
github
slack

Original URL: https://code.dennyzhang.com/string-to-integer

Connect with Denny In LinkedIn Or Slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.