[编程题]把字符串转换成整数
• 热度指数：471045 时间限制：C/C++ 1秒，其他语言2秒 空间限制：C/C++ 64M，其他语言128M
• 算法知识视频讲解

##### 输入描述:
`输入一个字符串,包括数字字母符号,可以为空`

##### 输出描述:
`如果是合法的数值表达则返回该数字，否则返回0`

## 输入

`"+2147483647"`

## 输出

```2147483647
```

`"1a33"`

## 输出

```0
```
```class Solution {
public:
int StrToInt(string str) {
if(str.empty())
return 0;
int symbol = 1;
if(str[0] == '-'){//处理负号
symbol = -1;
str[0] = '0'; //这里是‘0’ 不是0
}else if(str[0] == '+'){//处理正号
symbol = 1;
str[0] = '0';
}
int sum = 0;
for(int i=0;i<str.size();++i){
if(str[i] < '0' || str[i] > '9'){
sum = 0;
break;
}

sum = sum *10 + str[i] - '0';

}
return symbol * sum;

}
};

```

```class Solution {
public:
enum Status{kValid = 0,kInvalid};
int g_nStatus = kValid;

int StrToInt(string str) {
g_nStatus = kInvalid;
long long num = 0;
const char* cstr = str.c_str();
if( (cstr != NULL) && (*cstr != '\0') )
{
int minus = 1;
if(*cstr == '-')
{
minus = -1;
cstr++;
}
else if(*cstr == '+')
cstr++;

while(*cstr != '\0')
{
if(*cstr > '0' && *cstr < '9')
{
g_nStatus = kValid;
num = num*10 + (*cstr -'0');
cstr++;
if( ((minus>0) && (num > 0x7FFFFFFF)) ||
((minus<0) && (num > 0x80000000)) )
{
g_nStatus = kInvalid;
num = 0;
break;
}
}
else
{
g_nStatus = kInvalid;
num = 0;
break;
}
}

if(g_nStatus == kValid)
num = num * minus;

}
return (int)num;
}
};```

```class Solution {
public:
int StrToInt(string str) {
int n = str.size(), s = 1;
long long res = 0;
if(!n) return 0;
if(str[0] == '-') s = -1;
for(int i = (str[0] ==  '-' || str[0] == '+') ? 1 : 0; i < n; ++i){
if(!('0' <= str[i] && str[i] <= '9')) return 0;
res = (res << 1) + (res << 3) + (str[i] & 0xf);//res=res*10+str[i]-'0';
}
return res * s;
}
};```

```# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
numlist=['0','1','2','3','4','5','6','7','8','9','+','-']
sum=0
label=1#正负数标记
if s=='':
return 0
for string in s:
if string in numlist:#如果是合法字符
if string=='+':
label=1
continue
if string=='-':
label=-1
continue
else:
sum=sum*10+numlist.index(string)
if string not in numlist:#非合法字符
sum=0
break#跳出循环
return sum*label
```

```public class Solution {
public static boolean flag;
public static int StrToInt(String str) {
flag = false;
//判断输入是否合法
if (str == null || str.trim().equals("")) {
flag = true;
return 0;
}
// symbol=0,说明该数为正数;symbol=1，该数为负数;start用来区分第一位是否为符号位
int symbol = 0;
int start = 0;
char[] chars = str.trim().toCharArray();
if (chars[0] == '+') {
start = 1;
} else if (chars[0] == '-') {
start = 1;
symbol = 1;
}
int result = 0;
for (int i = start; i < chars.length; i++) {
if (chars[i] > '9' || chars[i] < '0') {
flag = true;
return 0;
}
int sum= result * 10 + (int) (chars[i] - '0');

if((sum-(int) (chars[i] - '0'))/10!=result){
flag=true;
return 0;
}

result=result * 10 + (int) (chars[i] - '0');
/*
* 本人认为java热门第一判断是否溢出是错误的，举个反例
* 当输入为value=2147483648时，在计算机内部的表示应该是-2147483648
* 显然value>Integer.MAX_VALUE是不成立的
*/
}
// 注意：java中-1的n次方不能用：(-1)^n .'^'异或运算
// 注意，当value=-2147483648时，value=-value
result = (int) Math.pow(-1, symbol) * result;
return result;
}
}```

```public int StrToInt(String str) {
if (str == null)
return 0;
int result = 0;
boolean negative = false;//是否负数
int i = 0, len = str.length();
/**
* limit 默认初始化为 负的 最大正整数 ，假如字符串表示的是正数
* 那么result(在返回之前一直是负数形式)就必须和这个最大正数的负数来比较，
* 判断是否溢出
*/
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;

if (len > 0) {
char firstChar = str.charAt(0);//首先看第一位
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;//在负号的情况下，判断溢出的值就变成了 整数的 最小负数了
} else if (firstChar != '+')//第一位不是数字和-只能是+
return 0;
if (len == 1) // Cannot have lone "+" or "-"
return 0;
i++;
}
multmin = limit / 10;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = str.charAt(i++)-'0';//char转int
if (digit < 0 || digit > 9)//0到9以外的数字
return 0;

//判断溢出
if (result < multmin) {
return 0;
}
result *= 10;
if (result < limit + digit) {
return 0;
}
result -= digit;
}
} else {
return 0;
}
//如果是正数就返回-result（result一直是负数）
return negative ? result : -result;
}```

``````/**
* 把字符串转成整数
* 题目描述
* 将一个字符串转换成一个整数，要求不能使用字符串转换整数的库函数。
* 数值为0或者字符串不是一个合法的数值则返回0
* 输入描述:
* 输入一个字符串,包括数字字母符号,可以为空
* 输出描述:
* 如果是合法的数值表达则返回该数字，否则返回0
* 示例1
* 输入
* +2147483647
* 1a33
* 输出
* 2147483647
* 0
*
* @author shijiacheng
* @date 2018/2/17
*/
public class StringToIntSolution {
public int StrToInt(String str) {
if (str.length()==0){
return 0;
}else if (str.length() == 1&&(str.charAt(0)=='-' ||str.charAt(0)=='+' )){
return 0;
}else {
int flag = 0;//1是整数，2是负数
boolean error = false;
char[] chars = str.toCharArray();
int i = 0;
if (chars[0]=='-'){
i++;
flag= 2;
}else if (chars[0]=='+'){
i++;
flag= 1;
}

int result = 0;
for (int j = i; j < chars.length; j++) {

if (chars[j]>='0'&&chars[j]<='9'){
result = result*10+(chars[j]-'0');
}else {
error = true;
break;
}
}

if (!error){
if (flag==2){
result = result*(-1);
}
return result;
}else {
return 0;
}
}
}

}
``````

```public int StrToInt(String str)
{
if (str.equals("") || str.length() == 0)
return 0;
char[] a = str.toCharArray();
int fuhao = 0;
if (a[0] == '-')
fuhao = 1;
int sum = 0;
for (int i = fuhao; i < a.length; i++)
{
if (a[i] == '+')
continue;
if (a[i] < 48 || a[i] > 57)
return 0;
sum = sum * 10 + a[i] - 48;
}
return fuhao == 0 ? sum : sum * -1;
}```

```public class Solution {
public int StrToInt(String str) {
int res = 0;

int symbol = 1;
boolean isInvalid = false;   // 区分非法输入和0
char[] arr = str.toCharArray();
int n = arr.length;

if (n <=  0 || str == null) {
isInvalid = true;
return 0;
}

if (arr[0] == '-')
symbol = -1;

for (int i = (arr[0] ==  '-' || arr[0] == '+') ? 1 : 0; i < n; ++i) {
if (!('0' <= arr[i] && arr[i] <= '9')) {
isInvalid = true;
return 0;
}
res = (res << 1) + (res << 3) + (arr[i] & 0xf); //res=res*10+arr[i]-'0'

// 溢出判断
if((symbol == 1 && res>Integer.MAX_VALUE) || (symbol == -1 && res < Integer.MIN_VALUE)) {
isInvalid = true;
return 0;
}
}

return res * symbol;
}
}

2. 正负号的处理
3. 溢出处理```

```#Python版
#思路：需判断一下首字母是否为+，-
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
if s is None:
return 0
lens = len(s)
if lens ==0:
return 0
res = 0
strat = 0
flag = 1
if s[0] == '+' or s[0] =='-':
strat = 1
if s[0] == '-':
flag = -1
for i in range(strat,lens):
if '0'<=s[i] and s[i] <= '9':
res = res*10+(ord(s[i])-ord('0'))
else:
return 0
if flag ==-1:
res = -res
return res

print Solution().StrToInt("1a33")```

```public class Solution {
public int StrToInt(String str) {
int res = 0;
//合法检测
if (!str.matches("\\+{0,1}\\-{0,1}[0-9]{1,}"))
return res;
int len = str.length();
for (int i = len - 1; i >= (str.charAt(0) == '-' || str.charAt(0) == '+' ? 1 : 0); i--) {
res += (int) Math.pow(10, (len - 1 - i)) * (str.charAt(i) - '0');
}
return str.charAt(0) == '-' ? -res : res;
}
}
```

```class Solution {
public:
int StrToInt(string str)
{
int m=str.length();
if(m==0) return 0;
int result=0,flag=1;
int index=str.find_first_not_of(' ');
if(str[index]=='+' || str[index]=='-')
flag = str[index++]=='-'? -1 : 1;
for(;index<m;index++)
{
if(str[index]>='0' && str[index]<='9')
{
result = result*10+(str[index]-'0');
if(result*flag > INT_MAX)
return INT_MAX;
if(result*flag < INT_MIN)
return INT_MIN;
}
else
{
result = 0;
break;
}
}
return result*flag;
}
};```

```public class Solution {
public int StrToInt(String str) {
if (str == null || "".equals(str)) return 0;
int len = str.length();
if (len == 1 && !isNumChar(str.charAt(0))) return 0;
//保存数值对应的字符
char[] numChars = new char[len];
int res = 0;
int index = 0;
char sign = '+';//保存符号
boolean isValid = true;
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (i == 0 && (c == '-' || c == '+')) {
sign = c;
continue;
}
if (isNumChar(c)) {
numChars[index++] = c;
} else {
isValid = false;
break;
}
}
if (!isValid) {
return 0;
}
for (int i = 0; i < index; i++) {
res += (numChars[i] - '0') * pow(10, index - i - 1);
}
return sign == '-' ? 0 - res : res;
}

/**
* 判断一个字符是否是数字
* @param c
* @return
*/
private boolean isNumChar(char c) {
return c >= '0' && c <= '9';
}

private int pow(int base, int exp) {
return (int) Math.pow(base, exp);
}
}```

```    public  int StrToInt(String str) {
if (str.length() == 0 ||str == null){
return 0;
}
long result = 0;

for(int i=0;i < str.length();i ++){
char c=str.charAt(i);
if(c >= '0' && c <= '9'){
result = result*10 + c-'0';
}else if(result != 0){
return 0;
}
}
result=str.charAt(0)=='-'? -result:result;
if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){
return 0;
}
return (int)result;
}```

```class Solution {
public:
int StrToInt(string str) {
if(str.length()<=0) return 0;
int i;
for(i=0;i<str.length();i++)
{
if(str[i]!=' ') break;
}
int flag=true;
if(str[i]=='+')
{
flag=true;
i++;
}
if(str[i]=='-')
{
flag=false;
i++;
}
int temp=0,digit=0;
for(int j=i;j<str.length();j++)
{
if(str[j]<'0'||str[j]>'9')
return 0;
else if(str[j]>='0'&&str[j]<='9')
{
digit=str[j]-'0';
if((flag==true&&temp>0x7fffffff)||(flag==false&&temp<(unsigned int)0x80000000))
return 0;
temp=temp*10+ digit;
}
}
return (flag==true)?temp:-temp;
}
};```

```看了高票的好些答案

public class Solution {
public int StrToInt(String str) {
if(str == null ||str.length()==0 || str.trim().equals("")) return 0;
char[] chars = str.trim().toCharArray();
int res=0,flag=1,start=0,tmp=0;
if(chars[0] == '-') {
flag = -1;
start = 1;
}
if(chars[0] == '+') start=1;
for(int i =start;i < chars.length;i++){
if(chars[i]>'9'||chars[i]<'0')
return 0;
//当前个位数字
int dight = (int)(chars[i]-'0');
tmp = res*10+dight;
//判断正数溢出
if(flag ==1 && res*10>Integer.MAX_VALUE - dight)
return 0;
//判断负数溢出
if(flag == -1 && res*10*flag < Integer.MIN_VALUE + dight)
return 0;
res = tmp;
}
return flag* res;
}
}```

# python solution

``````# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
try:
return int(s)
except:
return 0
``````

```public class Solution {
public int StrToInt(String str) {
boolean isPosotive = true;
char[] arr = str.toCharArray();
int sum = 0;
for(int i = 0; i < arr.length; i++) {
if (arr[i] == '+') {
continue;
}
else if (arr[i] == '-') {
isPosotive = false;
continue;
}
else if (arr[i] < '0' || arr[i] > '9') {
return 0;
}
sum = sum * 10 + (int)(arr[i] - '0');
}
if (sum == 0) {
return 0;
}
return isPosotive == true ? sum : -sum;
}
}
```

```public class Solution {

//1.字符串为空
//2.只有一个正或负号
//3.整数上下溢出 Integer.MAX_VALUE (2^31-1)  Integer.MIN_VALUE(-2^31)
public int StrToInt(String str) {

if(str == null ||str.length()==0){
return 0;
}
char[] c=str.toCharArray();
boolean minus = false;
int num = 0;
int i=0;
//数组溢出：下标大于数组长度！比如c.length ==1,当有c[1]出现时则数组溢出
if(c[i]=='+'){
++i;

}else if(c[i]=='-'){

++i;
minus=true;
}
if(i<c.length){
num = StrToIntCore(c,minus,i);
}else{
return num;
}
return num;

}

int StrToIntCore(char[] str,boolean minus,int i){
int num = 0;

for(int j = i;j<str.length;j++){

if(str[j]>='0'&&str[j]<='9'){

int flag = minus ? -1:1;
//str[j]-'0' 是为了把字符转为int数字
num = num*10 + flag*(str[j] - '0');
//
if((!minus&&num>Integer.MAX_VALUE)||(minus&&num<Integer.MIN_VALUE)){
num=0;
break;
}

}else{
num = 0;
break;
}
}
return num;

}

}

```

1191条回答 132873浏览

# 通过挑战的用户

• 2021-04-17 00:16:53
• 2021-04-16 22:41:51
• 2021-04-16 22:29:01
• 2021-04-16 21:31:34
• 2021-04-16 21:19:41

# 相关试题

• 扫描二维码，关注牛客网

• 下载牛客APP，随时随地刷题