题目:
需要考虑的是,这个数带不带符号,符号是"+" 还是”-“,可以通过字符串的第一个字符,使用flag记录一下这个符号,若没有符号,则从字符串头到字符串尾依次遍历,若有符号,则总第二个字符开始遍历,注意:在最后输出结果时,根据flag的记录,将符号恢复(若为”+“,则不用恢复)
实现代码如下:
package cn.strtoint;
/**
* @program: algorithm_learn
* @description: 把字符串转换成整数
* @author: Mr.Luo
* @create: 2020-06-11 14:12
*/
public class Main {
public static int StrToInt(String str){
if (str.length() == 0){
return 0;
}
char[] chars = str.toCharArray();
//判断是否存在符号位
int flag = 0;
if (chars[0] == '+'){
flag = 1;
}else if (chars[0] == '-'){
flag = 2;
}
int start = flag > 0 ? 1 : 0;
//保存结果
int res = 0;
for (int i = start; i < chars.length; i++) {
if (Character.isDigit(chars[i])){
int temp = chars[i] - '0';
res = res * 10 + temp;
}else {
return 0;
}
}
return flag == 2 ? -res : res;
}
public static void main(String[] args) {
String s = "-12312312";
System.out.println("使用库函数转换:" + Integer.valueOf(s));
System.out.println("使用自己写的方法转换:" + StrToInt(s));
}
}