敬请关注博客,后期不断更新优质博文,谢谢
每天坚持刷leetcode----字符串转整形
package leetcode.T008_StringToInteger;
/**
* @Title: Solution.java
* @Package leetcode.T008_StringToInteger
* @Description: TODO
* @author zhouzhixiang
* @date 2017-6-3 上午12:24:25
* @version V1.0
*/
public class Solution {
/**
* <pre>
* 原题
* 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.
*
* 题目大意
* 实现一个atoi函数,将字符串转成整形
* 要点:考虑所有的输入情况。
*
* 解题思路
* 前导字符是+或-或者没有,接下来输入的是数字,数字不能整数能表示的最大或最小数。
* 如果超过就返回对应的最小或者最小的值。
* </pre>
*
* @param str
* @return
*/
public static void main(String[] args) {
System.out.println(new Solution().atoi("3444ffff455544"));
}
public int atoi(String str){
// 如果字符串为空null,长度为0
if(str == null || str.length()==0 ){
return 0;
}
int start = 0;
// 对第一个字符进行判断
// 如果为空' '
if(str.charAt(start) == ' '){
while(str.charAt(start)==' '){
start++;
if(start >= str.length()){
// 输入的全部都是空格
return 0;
}
}
}
boolean positive = true;// true为正数,false为负数
// 如果为+
if(str.charAt(start)=='+'){
positive = true;
start++;
}else if(str.charAt(start)=='-'){
// 如果为-
positive = false;
start++;
}else if(str.charAt(start)>='0' && str.charAt(start)<='9'){
// 如果是0-9,进入下一步判断,将字符串转成整形
return cal(str,start,positive);
}else{
return 0;
}
// 第一个非空白字符是+或-,但也是最后一个字符
if(start>=str.length()){
return 0;
}
// 如果+或-后面接的不是数字
if(str.charAt(start)>'9' || str.charAt(start)<'0'){
return 0;
}else{
return cal(str,start,positive);
}
}
/**
*
* @Title: cal
* @Description: 将字符串数字转成整形
* @param @param str
* @param @param start
* @param @param positive
* @param @return
* @return int
* @throws
*/
private int cal(String str, int start, boolean positive) {
long result = 0;
while(start<str.length() && str.charAt(start)>='0' && str.charAt(start)<='9'){
result = result*10 + (str.charAt(start)-'0');
// 如果是正数
if(positive){
if(result>Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
}else{
if(-result<Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
}
start++;
}
if(positive){
return (int) result;
}else{
return (int) -result;
}
}
}
欢迎加入Java猿社区