LeetCode刷题--点滴记录015

15. 剑指 Offer 67. 把字符串转换成整数

要求

写一个函数 StrToInt,实现把字符串转换成整数这个功能。不能使用 atoi 或者其他类似的库函数。

首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。

当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。

该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。

注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。

在任何情况下,若函数不能进行有效的转换时,请返回 0。

解题

C++版本
#include <iostream>
using namespace std;

class Solution {
public:
    int strToInt(string str) {
        int res = 0;  // 拼接结果
        int bndry = INT_MAX / 10;
        int i = 0;
        int sign = 1; // 符号位
        int length = str.size();
        // 空字符串直接返回
        if (length == 0) 
            return 0;
        // 跳过首部空格
        while (str[i] == ' ')
            // 字符串全为空格直接返回
            if (++i == length) 
                return 0;
        if (str[i] == '-') // 处理符号位
            sign = -1;
        if (str[i] == '-' || str[i] == '+') 
            i++;
        // 处理数字位
        for (int j = i; j < length; j++) {
            if (str[j] < '0' || str[j] > '9') // 遇到首个非数字字符返回
                break;
            if (res > bndry || res == bndry && str[j] > '7') // 判断此次迭代是否越界
                return sign == 1 ? INT_MAX : INT_MIN;
            res = res * 10 + (str[j] - '0');  // 数字拼接
        }
        return sign * res;
    }
};

void test01()
{
    string str = "  -358  dfgc";
    Solution solution;
    cout << solution.strToInt(str) << endl;

}

int main()
{
    test01();

    system("pause");
    return 0;
}

在这里插入图片描述

Python版本
class Solution:
    def strToInt(self, str):
        res = 0  # 拼接结果
        i = 0  
        sign = 1 # 符号位
        length = len(str)
        int_max = 2 ** 31 - 1
        int_min = -2 ** 31
        bndry = 2 ** 31 // 10
        if not str: 
            return 0         # 空字符串,提前返回
        while str[i] == ' ':  # 空格
            i += 1
            if i == length: 
                return 0    # 字符串全为空格,提前返回
        if str[i] == '-': 
            sign = -1    # 保存负号
        if str[i] in '+-': 
            i += 1
        for j in range(i, length):
            if not '0' <= str[j] <= '9' : 
                break     # 遇到非数字的字符则跳出
            if res > bndry or res == bndry and str[j] > '7':
                return int_max if sign == 1 else int_min  # 数字越界处理
            res = 10 * res + ord(str[j]) - ord('0') # 数字拼接
        return sign * res

def test01():
    solution = Solution()
    str = '  -358  dfgc' 
    print(solution.strToInt(str))
            
if __name__=="__main__":
    test01()

在这里插入图片描述

Java版本
package com.hailei_01;

public class strToInt {
    public static void main(String[] args) {
        String str =  "  -358  dfgc";
        System.out.println(strToInt(str));
    }

    public static int strToInt(String str) {
        int res = 0;
        int bndry = Integer.MAX_VALUE / 10;
        int i = 0;
        int sign = 1;
        int length = str.length();
        if (length == 0)
            return 0;
        while (str.charAt(i) == ' ')
            if (++i == length)
                return 0;
        if (str.charAt(i) == '-')
            sign = -1;
        if (str.charAt(i) == '-' || str.charAt(i) == '+')
            i++;
        for (int j = i; j < length; j++) {
            if (str.charAt(j) < '0' || str.charAt(j) > '9')
                break;
            if (res > bndry || res == bndry && str.charAt(j) > '7')
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            res = res * 10 + (str.charAt(j) - '0');
        }
        return sign * res;
    }
}

在这里插入图片描述

希望本文对大家有帮助,上文若有不妥之处,欢迎指正

分享决定高度,学习拉开差距

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鲁棒最小二乘支持向量机

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值