码迷,mamicode.com
首页 > 其他好文 > 详细

String to Integer

时间:2016-07-23 07:26:53      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

Implement function atoi to convert a string to an integer.

If no valid conversion could be performed, a zero value is returned.

If the correct value is out of the range of representable values, INT_MAX(2147483647) or INT_MIN (-2147483648) is returned.

Example
"10" => 10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1

 1 public class Solution {
 2     /**
 3      * @param str: A string
 4      * @return An integer
 5      */
 6     public int atoi(String str) {
 7         if (str == null || str.length() == 0)
 8             return 0;
 9         str = str.trim();
10         if (str.length() == 1 && (str.equals("+") || str.equals("-") || str.equals(".") || str.equals("0"))) {
11             return 0;
12         }
13 
14         boolean isPositive = true;
15         long current = 0;
16 
17         for (int i = 0; i < str.length(); i++) {
18             if (i == 0 && str.charAt(i) == +) {
19                 continue;
20             } else if (i == 0 && str.charAt(i) == -) {
21                 isPositive = false;
22             } else if ((str.charAt(i) == . && i == str.length() - 1)
23                     || (str.charAt(i) == . && i == str.length() - 2 && str.charAt(str.length() - 1) == 0)) {
24                 break;
25             } else if (str.charAt(i) >= 0 && str.charAt(i) <= 9) {
26                 current = current * 10 + str.charAt(i) - 0;
27                 if (isPositive && current > Integer.MAX_VALUE)
28                     return Integer.MAX_VALUE;
29                 if (!isPositive && -current < Integer.MIN_VALUE)
30                     return Integer.MIN_VALUE;
31             } else {
32                 break;
33             }
34         }
35 
36         if (!isPositive) {
37             current = -current;
38         }
39 
40         return (int) current;
41     }
42 }

 

 

String to Integer

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5697755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!