为了提高面试流程效率,方便用java写一段将字符串转成整数的函数给我看一下吗,简单看一下代码基本功。
要求:不要调用parseInt等转换函数。按位读取字符串里的字符进行处理将字符串转化为整数,
不考虑整数溢出问题,给定的输入一定是合法输入不包含非法字符,字符串头尾没有空格,
考虑字符串开头可能有正负号。public int StringToInt(String str)
import javax.net.ssl.SSLContext;
/**
* 字符串转为int
* @author IT
* @Date 2018年10月16日
*/
public class StringToInt {
public static void main(String[] args) {
String s = "2018";
try {
System.out.println("转换结果"+parse(s));
} catch (Exception e) {
e.printStackTrace();
}
}
public static int parse(String s) throws Exception{
int result = 0;
if (s == null || s.length() == 0) {
throw new Exception("字符串为空");
}
String s1 = s;
// if(s.startsWith("-")) {
// s1 = s.substring(1, s.length());
// }
for (int i = 0; i < s1.length(); i++) {
if (i==0) {
if(s1.charAt(i) == '-' ){
continue;
}
}else{
if(s1.charAt(i)>'9' || s1.charAt(i)<'0'){
throw new Exception("字符串格式错误");
}
}
result = result * 10;
result = ( result + s1.charAt(i) ) - '0';
System.out.println("每一位数:"+s1.charAt(i));
System.out.println("每一次累加结果:"+result);
}
return result;
}
}