[Leetcode] String to Integer (atoi) (Java)

来源:互联网 发布:淘宝网歌莉娅 编辑:程序博客网 时间:2024/05/29 07:38

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.

将字符串转换成数字,考虑正负数,空串,整形int越界等,字符串中出现类似 -0012a45 则返回 -12,若大于Integer.MAX_VALUE则返回Integer.MAX_VALUE,若小于Integer.MIN_VALUE则返回Integer.MIN_VALUE

public class StringtoInteger {public int atoi(String str) {if(str.length()<1)return 0;boolean flag = true;int offset=0;long result=0;while(str.charAt(offset)==' '){offset++;}if(str.charAt(offset)=='-'){flag = false;offset++;}else if(str.charAt(offset)=='+'){offset++;}for(int i=offset;i<str.length();i++) {if(str.charAt(i)>'9'||str.charAt(i)<'0') {break;}result=result*10+str.charAt(i)-'0';}result = flag?result:-result;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) {String string = "-2147483649";System.out.println(new StringtoInteger().atoi(string));}}

需要注意int越界

0 0