题解 | #把字符串转换成整数#
把字符串转换成整数
https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e
import java.util.*; public class Solution { public int StrToInt(String str) { char[] ch = str.toCharArray(); if(ch == null || ch.length == 0) { return 0; } int flg = 1; if(ch[0] == '+') { ch[0] = '0'; } if(ch[0] == '-') { flg = -1; ch[0] = '0'; } int sum = 0; for(int i = 0; i < ch.length; i++) { if(ch[i] < '0' || ch[i] > '9') { return 0; } sum = sum * 10 + ch[i] - '0'; } return flg * sum; } }