返回介绍

String to Integer

发布于 2025-02-22 13:01:34 字数 2189 浏览 0 评论 0 收藏 0

Source

Implement function atoi to convert a string to an integer.

If no valid conversion could be performed, a zero value is returned.

If the correct value is out of the range of representable values,
INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Example
"10" => 10

"-1" => -1

"123123123123123" => 2147483647

"1.0" => 1

题解

经典的字符串转整数题,边界条件比较多,比如是否需要考虑小数点,空白及非法字符的处理,正负号的处理,科学计数法等。最先处理的是空白字符,然后是正负号,接下来只要出现非法字符(包含正负号,小数点等,无需对这两类单独处理) 即退出,否则按照正负号的整数进位加法处理。

Java

public class Solution {
  /**
   * @param str: A string
   * @return An integer
   */
  public int atoi(String str) {
    if (str == null || str.length() == 0) return 0;

    // trim left and right spaces
    String strTrim = str.trim();
    int len = strTrim.length();
    // sign symbol for positive and negative
    int sign = 1;
    // index for iteration
    int i = 0;
    if (strTrim.charAt(i) == '+') {
      i++;
    } else if (strTrim.charAt(i) == '-') {
      sign = -1;
      i++;
    }

    // store the result as long to avoid overflow
    long result = 0;
    while (i < len) {
      if (strTrim.charAt(i) < '0' || strTrim.charAt(i) > '9') {
        break;
      }
      result = 10 * result + sign * (strTrim.charAt(i) - '0');
      // overflow
      if (result > Integer.MAX_VALUE) {
        return Integer.MAX_VALUE;
      } else if (result < Integer.MIN_VALUE) {
        return Integer.MIN_VALUE;
      }
      i++;
    }

    return (int)result;
  }
}

源码分析

符号位使用整型表示,便于后期相乘相加。在 while 循环中需要注意判断是否已经溢出,如果放在 while 循环外面则有可能超过 long 型范围。

复杂度分析

Reference

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文