# 把字符串转换成整数（字符串）

思路一：

``````public class Solution {
public int StrToInt(String str) {
if (str == null || str.length() == 0)
return 0;
char[] chars = str.toCharArray();
int symbol = 1;
if (chars[0] == '-')
symbol = -1;
int sum = 0;
for (int i = (chars[0] == '+' || chars[0] == '-') ? 1:0; i <chars.length; i++)
{
if (chars[i] < '0' || chars[i] > '9')
return 0;
else
sum  = sum * 10 + chars[i] - '0';
}
return sum * symbol;
}
}``````

``````public class Solution {
public int StrToInt(String str) {
if (str == null || str.length() == 0)
return 0;
char[] chars = str.toCharArray();
int symbol = 1;
if (chars[0] == '-')
symbol = -1;
int sum = 0;
for (int i = (chars[0] == '+' || chars[0] == '-') ? 1:0; i <chars.length; i++)
{
if (chars[i] < '0' || chars[i] > '9')
return 0;
else
sum  = (sum << 1) + (sum << 3) + (chars[i] & 0xf);
}
return sum * symbol;
}
}``````

int 范围-2147483648 到 2147483647

``````public class Solution {
public static void main(String[] args) {
Solution so = new Solution();
String s = "2147483648";
System.out.println(so.StrToInt(s));    //输出为0
}
public int StrToInt(String str) {
if (str == null || str.length() == 0)
return 0;
char[] chars = str.toCharArray();
int symbol = 1;
if (chars[0] == '-')
symbol = -1;
long sum = 0;
for (int i = (chars[0] == '+' || chars[0] == '-') ? 1:0; i <chars.length; i++)
{
if (chars[i] < '0' || chars[i] > '9')
return 0;
else
sum  = (sum << 1) + (sum << 3) + (chars[i] & 0xf);
if (symbol == 1 && sum > Integer.MAX_VALUE || (symbol == -1 && sum < Integer.MIN_VALUE))
return 0;
}
return (int)(sum * symbol);
}
}``````

原文作者：when_bounce
原文地址: https://blog.csdn.net/DirBee/article/details/78656007
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。