【Leetcode】String to Integer (atoi)

来源:互联网 发布:csalex老帅哥淘宝店 编辑:程序博客网 时间:2024/05/08 22:58

题目链接: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.

思路:
各种边界会烦死人的。。。

算法:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public int myAtoi(String str) {  
  2.     if (str == null || str.equals(""))  
  3.         return 0;  
  4.     str = str.trim();  
  5.     String flag = "+";  
  6.     int i = 0;  
  7.     if ("+".equals(str.charAt(0) + "")) {  
  8.         i++;  
  9.         flag = "+";  
  10.     } else if ("-".equals(str.charAt(0) + "")) {  
  11.         i++;  
  12.         flag = "-";  
  13.     }  
  14.     double sum = 0;  
  15.     while (i < str.length() && str.charAt(i) <= '9' && str.charAt(i) >= '0') {  
  16.         sum = sum * 10 + Integer.parseInt("" + str.charAt(i));  
  17.         i++;  
  18.     }  
  19.     if (flag.equals("-")) {  
  20.         sum = -sum;  
  21.     }  
  22.     if (sum > Integer.MAX_VALUE) {  
  23.         sum = Integer.MAX_VALUE;  
  24.     }  
  25.     if (sum < Integer.MIN_VALUE) {  
  26.         sum = Integer.MIN_VALUE;  
  27.     }  
  28.     return (int) sum;  
  29. }  
1 0
原创粉丝点击