LeetCode : atoi My solution
2014-10-14 16:29
363 查看
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.
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.
public class Solution { public int atoi(String str) { if (str == null || str.length() == 0) { return 0; } str = str.trim(); if (str.length() == 0) { return 0; } long result = 0; int negative = 1; int Max = Integer.MAX_VALUE; int Min = Integer.MIN_VALUE; int index = 0; if (str.charAt(index) == '+') { index++; } else if (str.charAt(index) == '-') { negative = -1; index++; } for (; index < str.length(); index++) { char thisBit = str.charAt(index); if (thisBit > '9' || thisBit < '0') { break; } else { result = result * 10 + (thisBit - '0'); if (result > Max && negative == 1){ break; } } } result = result * negative; if (result > Max) { return Max; } if (result < Min) { return Min; } return (int) result; } }
相关文章推荐
- LeetCode-String to Integer (atoi)-My Java Solution
- [Leetcode]Letter Combinations of a Phone Number My Submissions Question Solution
- LeetCode My solution: N-Queens II
- [Leetcode] Minimum Window Substring My Submissions Question Solution
- (leetcode) 238. Product of Array Except Self My Submissions QuestionEditorial Solution
- LeetCode:String to Integer (atoi) -one solution coded by c language
- LeetCode My Solution: Minimum Depth of Binary Tree
- leetcode 3. Longest Substring Without Repeating Characters My Submissions QuestionEditorial Solution
- Leetcode 8. String to Integer (atoi) The Solution of Python
- Leetcode 111. Minimum Depth of Binary Tree My Submissions QuestionEditorial Solution
- The Solution to Leetcode 137 Single Number II
- 刷题的日常[Leetcode]——8)String to Integer(atoi)
- leetcode 8. String to Integer (atoi)
- Leetcode: String to Integer (atoi)
- LeetCode:String to Integer (atoi)
- [Leetcode] String to Integer (atoi)
- [LeetCode] Combination Sum, Solution
- [LeetCode] String to Integer (atoi) 解题报告
- [LeetCode] Decode Ways, Solution
- [LeetCode] Palindrome Partitioning, Solution