【每日一题】【字符串与数字互转】【去除空格】【大数处理】2021年12月12日-8. 字符串转换整数 (atoi)

2023-02-12,,,,

请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数(类似 C/C++ 中的 atoi 函数)。

函数 myAtoi(string s) 的算法如下:

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/string-to-integer-atoi
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

//去除空格、看首位符号,遍历看每位数
class Solution {
public int myAtoi(String s) {
String str = s.trim();
if(str.length() == 0) { //应该是去除空格后的
return 0;
}
char symbol = '+';
if(str.charAt(0) == '-' || str.charAt(0) == '+') {
symbol = str.charAt(0);
str = str.substring(1); //此方法为小写
}
long num = 0;
for(char c : str.toCharArray()) {
if(c >= '0' && c <= '9') {
if(symbol == '+') {
num = num * 10 + (c - '0');
} else {
num = num * 10 - (c - '0');
}
if(num >= Integer.MAX_VALUE) {
num = Integer.MAX_VALUE;
}
if(num <= Integer.MIN_VALUE) {
num = Integer.MIN_VALUE;
}
} else {
break;
}
}
return (int)num;
}
}

【每日一题】【字符串与数字互转】【去除空格】【大数处理】2021年12月12日-8. 字符串转换整数 (atoi)的相关教程结束。

《【每日一题】【字符串与数字互转】【去除空格】【大数处理】2021年12月12日-8. 字符串转换整数 (atoi).doc》

下载本文的Word格式文档,以方便收藏与打印。