完整题干:
用户经常需要将只包含数字和小数点的字符串转换为数,例如在数据库管理系统中,在命令行方式下输入一条命令“list for 基本工资>3000”,系统以字符串的形式接收,但是系统在计算时必须将字符串"3000"还原为数字3000才行。
编写一个方法 atoint 实现字符串到 int 型整数的转换。例如 atoint("123")的结果为123。
个人答案:
(1)java版本
public class Solution {
public int myAtoi(String str) {
int len = str.length();
// str.charAt(i) 方法回去检查下标的合法性,一般先转换成字符数组
char[] charArray = str.toCharArray();
// 1、去除前导空格
int index = 0;
while (index < len && charArray[index] == ' ') {
index++;
}
// 2、如果已经遍历完成(针对极端用例 " ")
if (index == len) {
return 0;
}
// 3、如果出现符号字符,仅第 1 个有效,并记录正负
int sign = 1;
char firstChar = charArray[index];
if (firstChar == '+') {
index++;
} else if (firstChar == '-') {
index++;
sign = -1;
}
// 4、将后续出现的数字字符进行转换
// 不能使用 long 类型,这是题目说的
int res = 0;
while (index < len) {
char currChar = charArray[index];
// 4.1 先判断不合法的情况
if (currChar > '9' || currChar < '0') {
break;
}
// 题目中说:环境只能存储 32 位大小的有符号整数,因此,需要提前判:断乘以 10 以后是否越界
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (currChar - '0') > Integer.MAX_VALUE % 10)) {
return Integer.MAX_VALUE;
}
if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && (currChar - '0') > -(Integer.MIN_VALUE % 10))) {
return Integer.MIN_VALUE;
}
// 4.2 合法的情况下,才考虑转换,每一步都把符号位乘进去
res = res * 10 + sign * (currChar - '0');
index++;
}
return res;
}
public static void main(String[] args) {
Solution solution = new Solution();
String str = "2147483646";
int res = solution.myAtoi(str);
System.out.println(res);
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
}
}
import java.util.Scanner;
public class solution2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = "+123abc"; //输入要转化的字符串的值
int num = Solution.myAtoi(str); //调用myatoi的方法
System.out.println("The converted number is:"+num); //转化好的数字
class solution { //定义字符串转为整数的方法
public int myAtoi(String str) {
if (str == null || str.length() == 0)//如果字符串为空,输出0
return 0;
String res = "";
//过滤开头的空格直至第一个非空字符
int i = 0;
while (i < str.length() && str.charAt(i) == ' ') {
i++;//是数字就添加
}
str = str.substring(i);//没有数字的情况
if (str.equals("")) {
return 0;
}
int flag = 1;//正数默认为1
if (str.charAt(0) != '-' && str.charAt(0) != '+' && (str.charAt(0) > '9' || str.charAt(0) < '0')) {
return 0;//判断是否有符号,因为会有+123这种情况
} else if (str.charAt(0) == '-' || str.charAt(0) == '+') {
i = 1;
while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
i++;//当第一位不是符号时
}
if (i > 1) {
res = str.substring(1, i);
if (str.charAt(0) == '-') {
flag = -1;//负数flag为-1
}
} else {
return 0;
}
} else {
i = 0;
while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
i++;
}
res = str.substring(0, i);
}
//去除开头的0
i = 0;
while (i < res.length() && res.charAt(i) == '0') {
i++;
}
res = res.substring(i);
if (res.equals("")) {
return 0;
}
//如果数字大于Integer.MAX_VALUE,则直接返回Integer.MAX_VALUE;
//如果数字小于Integer.MIN_VALUE,则直接返回Integer.MIN_VALUE;
String minnum = "";
if (flag == -1) {
minnum = "2147483648";
if (res.length() < minnum.length()) {
res = "-" + res;
return Integer.valueOf(res);
} else if (res.length() > minnum.length()) {
return Integer.MIN_VALUE;
} else {
for (int j = 0; j < minnum.length(); j++) {
if (res.charAt(j) > minnum.charAt(j)) {
return Integer.MIN_VALUE;
} else if (res.charAt(j) < minnum.charAt(j)) {
res = "-" + res;
return Integer.valueOf(res);
}
}
return Integer.MIN_VALUE;
}
} else {
minnum = "2147483647";
if (res.length() < minnum.length()) {
return Integer.valueOf(res);
} else if (res.length() > minnum.length()) {
return Integer.MAX_VALUE;
} else {
for (int j = 0; j < minnum.length(); j++) {
if (res.charAt(j) > minnum.charAt(j)) {
return Integer.MAX_VALUE;
} else if (res.charAt(j) < minnum.charAt(j)) {
return Integer.valueOf(res);
}
}
return Integer.MAX_VALUE;
}
}
}
}
}
}
(2)python版本
def my_atoi(num_string):
if num_string == '':
return 0
else:
try:
f = float(num_string) #浮点
i = int(f) #整数
except:
return 0
else:
return i
if __name__ == '__main__':
s0 = "123"
s1 = " -123.456 "
s2 = " +123. "
s3 = ' -123..456 '
s4 = ' '
print(my_atoi(s0))
print(my_atoi(s1))
print(my_atoi(s2))
print(my_atoi(s3))
print(my_atoi(s4))
参考答案:
package chap3.excercise;
import java.util.Scanner;
public class Excercise4 {
/**
* 编写一个方法atoint实现字符串到浮点数的转换
*/
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
System.out.print("输入一个整数数字串:");
String str = scn.next(); //接收一个字符串
System.out.println("转换完的整数为:"+atoint(str.toCharArray())); //将字符串转换为字符数组类型
}
static int atoint(char[] string){
int sum = 0;
for(int i=0; i<string.length; i++){ /*整数部分的转换*/
int x = string[i]-'0';
sum=sum*10+x;
}
return sum;
}
}