zoukankan      html  css  js  c++  java
  • [LeetCode] String to Integer (atoi)

    代码:

     1 class Solution {
     2 public:
     3     int atoi(string str) {
     4         int num = 0;
     5         int sign = 1;
     6         const int n = str.size();
     7         int i = 0;
     8 
     9         while (str[i] == ' ' && i < n)
    10             i++;
    11 
    12         if (str[i] == '+') {
    13             i++;
    14         }
    15         else if (str[i] == '-') {
    16             sign = -1;
    17             i++;
    18         }
    19 
    20         if (str[i] == '+' || str[i] == '-')
    21             return 0;
    22 
    23 
    24         for (; i < n; i++) {
    25             if (str[i] < '0' || str[i] > '9')
    26                 return num * sign;
    27             if (num > INT_MAX / 10 || (num == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10) ){
    28                 return sign == -1 ? INT_MIN : INT_MAX;
    29             }
    30             num = num * 10 + str[i] - '0';
    31         }
    32         return num * sign;
    33     }
    34 };
     1 class Solution {
     2 public:
     3     int atoi(string str) {
     4         int num = 0;
     5         int sign = 1;
     6         const int n = str.size();
     7         int i = 0;
     8 
     9         while (str[i] == ' ' && i < n)
    10             i++;
    11 
    12         if (str[i] == '+') {
    13             i++;
    14         }
    15         else if (str[i] == '-') {
    16             sign = -1;
    17             i++;
    18         }
    19 
    20         if (str[i] == '+' || str[i] == '-')
    21             return 0;
    22 
    23 
    24         for (; i < n; i++) {
    25             if (str[i] < '0' || str[i] > '9')
    26                 return num * sign;
    27             if (num > INT_MAX / 10 || (num == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10) ){
    28                 return sign == -1 ? INT_MIN : INT_MAX;
    29             }
    30             num = num * 10 + str[i] - '0';
    31         }
    32         return num * sign;
    33     }
    34 };

    杂记:

    1. 纯粹的细节题,但是感觉好多细节不明。

  • 相关阅读:
    网页版台球小游戏
    代码写响应式时钟效果
    如何使用SVN?
    TP框架---View视图层---模板继承(举例说明)
    ThinkPhp框架:文件上传
    ThinkPhp框架:验证码功能
    ThinkPhp框架:父类及表单验证
    ThinkPhp框架对“数据库”的基本操作
    对thinkphp的命名空间的理解
    控制器操作方法的调用
  • 原文地址:https://www.cnblogs.com/Azurewing/p/4313561.html
Copyright © 2011-2022 走看看