0
点赞
收藏
分享

微信扫一扫

LeetCode(剑指 Offer)- 67. 把字符串转换成整数


题目链接:​​点击打开链接​​

题目大意:略。

解题思路:略。

相关企业

  • Facebook
  • 微软(Microsoft)
  • 亚马逊(Amazon)
  • 谷歌(Google)
  • 彭博(Bloomberg)
  • 字节跳动
  • 百度

AC 代码

  • Java
// 解决方案(1)
class Solution {
public int strToInt(String str) {
str = str.trim();
boolean fisrtNumFlag = false;
int sign = 1;
char[] chars = str.toCharArray();
char c;
long res = 0;
int num = -1;

for (int i = 0; i < chars.length; i++) {
c = chars[i];
// 字母
if (isAlphabet(c)) {
if (!fisrtNumFlag) {
return 0;
}
break;
}

// 符号
if (isSign(c)) {
if (i > 0 && !fisrtNumFlag) {
return 0;
}
if (i == 0) {
sign = c == '+' ? 1 : -1;
continue;
}
}

// 其他
if ((num = handleNumber(c)) == -1) {
break;
}

// 数字
fisrtNumFlag = true;
res = res * 10 + num;
if (sign > 0 && res > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (sign < 0 && -res < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
}

return (int)(sign * res);
}

private int handleNumber(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
return -1;
}

private boolean isAlphabet(char c) {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z';
}

private boolean isSign(char c) {
return c == '+' || c == '-';
}
}

// 解决方案(2)
class Solution {
public int strToInt(String str) {
char[] c = str.trim().toCharArray();
if(c.length == 0) return 0;
int res = 0, bndry = Integer.MAX_VALUE / 10;
int i = 1, sign = 1;
if(c[0] == '-') sign = -1;
else if(c[0] != '+') i = 0;
for(int j = i; j < c.length; j++) {
if(c[j] < '0' || c[j] > '9') break;
if(res > bndry || res == bndry && c[j] > '7') return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
res = res * 10 + (c[j] - '0');
}
return sign * res;
}
}

// 解决方案(3)
class Solution {
public int strToInt(String str) {
int res = 0, bndry = Integer.MAX_VALUE / 10;
int i = 0, sign = 1, 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;
}
}
  • C++
class Solution {
public:
int strToInt(string str) {
int res = 0, bndry = INT_MAX / 10;
int i = 0, sign = 1, 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;
}
};


举报

相关推荐

0 条评论