String to Integer (atoi)(leetcode8)

本文详细阐述了如何实现atoi函数,用于将字符串转换为整数,并着重讨论了如何处理溢出问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

 

The heart of this problem is dealing with overflow. A direct approach is to store the number as a string so we can evaluate at each step if the number had indeed overflowed. There are some other ways to detect overflow that requires knowledge about how a specific programming language or operating system works.

A desirable solution does not require any assumption on how the language works. In each step we are appending a digit to the number by doing a multiplication and addition. If the current number is greater than 214748364, we know it is going to overflow. On the other hand, if the current number is equal to 214748364, we know that it will overflow only when the current digit is greater than or equal to 8. Remember to also consider edge case for the smallest number, –2147483648 (–231). 

 

 1     private static final int maxDiv10 = Integer.MAX_VALUE/10;
 2     public int myAtoi(String str) {
 3         String s = str.trim();
 4         int i = 0, sign = 1;
 5         if(i < s.length() && s.charAt(0) == '+') {
 6             sign = 1;
 7             i++;
 8         } else if(i < s.length() && s.charAt(0) == '-'){
 9             sign = -1;
10             i++;
11         }
12         int num = 0;
13         while(i < s.length() && Character.isDigit(s.charAt(i))){
14             int digit = Character.getNumericValue(s.charAt(i));
15             if(num > maxDiv10 || num == maxDiv10 && digit >7){
16                 return sign == 1 ? Integer.MAX_VALUE:Integer.MIN_VALUE;
17             }
18             num = num * 10 + digit;
19             i++;
20         }
21         return num * sign;
22     }

 

转载于:https://www.cnblogs.com/caomeibaobaoguai/p/4895016.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值