字符串转换整数

要考虑的特殊情况有:

1、字符串开头空格(删除即可)

StringName = StringName.trim();

2、符号:用boolean判断第一个字符是+、-。没有默认为+(后续就只需要判断添加字符是否是数字字符,用boolean也解决了字符串中多个+-号问题)

3、数字长度是否超限:遍历字符时直接添加进long中并且判断大小是否超限,超限则直接返回大或小极限

代码实现:

import java.util.Scanner;

public class Demo {
    public static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        String num = sc.nextLine();
         int result = Solution.myAtoi(num);
         System.out.println(result);
    }
}
class Solution {
    public static int myAtoi(String s) {
        s = s.trim();
        if (s.length() == 0) {
            return 0;
        }

        boolean negative = false;
        int i = 0;
        if (s.charAt(0) == '-') {
            negative = true;
            i++;
        } else if (s.charAt(0) == '+') {
            i++;
        }

        long result = 0;
        while (i < s.length() && Character.isDigit(s.charAt(i))) {
            result = result * 10 + (s.charAt(i) - '0');
            if (!negative && result > Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;
            } else if (negative && -result < Integer.MIN_VALUE) {
                return Integer.MIN_VALUE;
            }
            i++;
        }

        if (negative) {
            result = -result;
        }

        return (int) result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值