Implement atoi to convert a string to an integer.
2016-12-17 11:45
399 查看
package com.dengpf.StringToInteger; /** * Created by kobe73er on 16/12/17. */ public class Solution { public int myAtoi(String str) { if (str == null || str.length() < 1) return 0; // trim white spaces str = str.trim(); char flag = '+'; // check negative or positive int i = 0; if (str.charAt(0) == '-') { flag = '-'; i++; } else if (str.charAt(0) == '+') { i++; } // use double to store result double result = 0; // calculate value while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') { result = result * 10 + (str.charAt(i) - '0'); i++; } if (flag == '-') result = -result; // handle max and min if (result > Integer.MAX_VALUE) return Integer.MAX_VALUE; if (result < Integer.MIN_VALUE) return Integer.MIN_VALUE; return (int) result; } public static void main(String args[]) { Solution solution = new Solution(); System.out.println(solution.myAtoi("")); } }
相关文章推荐
- leetcode 8 Implement atoi to convert a string to an integer.
- Implement atoi to convert a string to an integer.
- Write a function to convert an IPv4 Address in string format to an unsigned integer
- How Do I Convert an Integer to a String in Excel VBA
- Convert a string to an enum
- LeetCode: String to Integer (atoi)
- LeetCode:String to Integer (atoi)
- Convert a string to an enum.
- In Java, how do I read/convert an InputStream to a String? - Stack Overflow
- String to Integer (atoi)
- [LeetCode] String to Integer (atoi) 解题报告
- LeetCode 8 - String to Integer (atoi)
- Leetcode : String to Integer (atoi)
- How can I convert a floating-point value to an integer in C?
- leetcode 54: String to Integer (atoi)
- 【LeetCode with Python】 String to Integer (atoi)
- leetcode 54: String to Integer (atoi)
- 数字转换为字符串:String:convert an int to a string
- [LeetCode] String to Integer (atoi)
- Leetcode: String to Integer (atoi)