LeetCode String to Integer (atoi)

原题链接在这里:https://leetcode.com/problems/string-to-integer-atoi/

题目:

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.

题解:

先把前后的空格去掉,然后取首个符号位。

Note溢出,若是res已经大于Intger.MAX_VALUE/10, res*10就会溢出,若是res == Integer.MAX_VALUE/10, 但最后一位比8大都会溢出,因为Integer的范围是 -2147483648 到 2147483647, 最后一位若是8的话就会溢出, 因为Integer.MAX_VALUE 的最后一位是7.

Time Complexity: O(str.length()). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int myAtoi(String str) {
 3         if(str == null || str.length() == 0){
 4             return 0;
 5         }
 6         
 7         //去掉前后空格
 8         str = str.trim();
 9         int i = 0;
10         char flag = '+';
11         //首个char是符号
12         if(str.charAt(i) == '+'){
13             i++;
14         }else if(str.charAt(i) == '-'){
15             flag = '-';
16             i++;
17         }
18         
19         int res = 0;
20         while(i<str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){
21             //溢出
22             if(res > Integer.MAX_VALUE/10 || (res == Integer.MAX_VALUE/10 && str.charAt(i)>='8')){
23                 return flag == '+' ? Integer.MAX_VALUE : Integer.MIN_VALUE;
24             }
25             res = res*10 + (str.charAt(i)-'0');
26             i++;
27         }
28         if(flag == '-'){
29             res = -res;
30         }
31         return res;
32     }
33 }

类似Reverse Integer.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5139690.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值