题目
将整数字符串转成整数值
java代码
package com.lizhouwei.chapter5;
/**
* @Description: 将整数字符串转成整数值
* @Author: lizhouwei
* @CreateDate: 2018/4/23 22:14
* @Modify by:
* @ModifyDate:
*/
public class Chapter5_5 {
public int convert(String str) {
char[] chars = str.toCharArray();
if(!isValid(chars)){
return 0;
};
boolean posi = chars[0] != '-' ? true : false;
int minq = Integer.MIN_VALUE / 10;
int minr = Integer.MIN_VALUE % 10;
int res = 0;
int cur = 0;
for (int i = posi ? 0 : 1; i < chars.length; i++) {
cur = '0' - chars[i];
if (res < minq || (res == minq && cur < minr)) {
return 0;
}
res = res * 10 + cur;
}
if (posi && res == Integer.MIN_VALUE) {
return 0;
}
return posi ? -res : res;
}
public boolean isValid(char[] chars) {
if (chars[0] != '-' && (chars[0] < '0' || chars[0] > '9')) {
return false;
}
if (chars[0] == '-' && (chars.length == 1 || chars[0] == '0')) {
return false;
}
if (chars[0] == '0' && (chars.length > 1)) {
return false;
}
for (int i = 0; i < chars.length; i++) {
if (chars[i] < '0' || chars[i] > '9') {
return false;
}
}
return true;
}
//测试
public static void main(String[] args) {
Chapter5_5 chapter = new Chapter5_5();
String str1 = "2147483647";
String str2 = "2147483648";
String str3 = "-2147483648";
String str4 = "02147483648";
System.out.println("2147483647转换为整数:" + chapter.convert(str1));
System.out.println("2147483648转换为整数,会溢出:" + chapter.convert(str2));
System.out.println("-2147483648转换为整数,不会溢出:" + chapter.convert(str3));
System.out.println("02147483648转换为整数,不符合书写习惯:" + chapter.convert(str4));
}
}
结果