算法系列——String to Integer (atoi)

来源:互联网 发布:北京大学网络教育官网 编辑:程序博客网 时间:2024/06/06 17:25

题目描述

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.

解题思路

实现字符串转整型的函数。注意处理边界问题和符合问题。

算法实现

public class Solution {    public int myAtoi(String str) {        int head=0;        long sum=0;        int flag=1;        if(str==null || str=="")            return 0;        while(str.charAt(head)==' ')            head++;        if(str.charAt(head)=='-'){            flag=-1;            head++;        }        else if(str.charAt(head)=='+'){            head++;        }        while(str.charAt(head)>='0'&&str.charAt(head)<='9'){            sum=sum*10+str.charAt(head)-'0';            if(sum*flag>Integer.MAX_VALUE)                return Integer.MAX_VALUE;            if(sum*flag<Integer.MIN_VALUE)                return Integer.MIN_VALUE;            head++;        }        return (int)sum*flag;    }}
原创粉丝点击