String to Integer (atoi)

题目描述
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.
题目出处: https://oj.leetcode.com/problems/string-to-integer-atoi/

解题思路
本题实现字符串转换为整数的函数。

相关知识点
(1)根据下标删除字符串中的字符
String中并没有相应的函数,处理的方法是使用StringBuffer。
StringBuffer sb = new StringBuffer(str);
sb.deleteCharAt(0);//删除下标为0的字符


(2)String中的subString(int beginIndex, int endIndex)的方法中endIndex参数并不包括在内,也就是说是从beginIndex到endIndex-1。

(3)String中compareTo(String anotherString)中的比较规则是不管长度大小,总是从第一个字符开始比较,如果相同则返回0,大于或者小于返回两个的差值(一个大于0,一个小于0)。

自己的代码
package leetcode;

public class StringToIntegerAtoi {
	public int atoi(String str) {
		if(str == null) return 0;
		//将头部的空格去掉
		StringBuffer sb = new StringBuffer(str);
		for(int i = 0; i < sb.length(); i++){
			if(sb.charAt(i) == ' ') {
				sb.deleteCharAt(i);
				i = -1;
			}
			else break;
		}
		str = sb.toString();
		if(str.length() == 0) return 0;
		//判断首字符是否为“ + - 数字”
		int sign = 1;
		char firChar = str.charAt(0);
		if(firChar != '+' && firChar != '-' && !(firChar >= '0' && firChar <= '9'))
			return 0;
		if(firChar == '-' || firChar == '+'){
			if(str.length() == 1) return 0;
			else if(firChar == '-') sign = 0;
			str = str.substring(1);
		}
		//判断字符中是否全为数字,然后将非数字字符前的数字全部提取出来
		for(int i = 0; i < str.length(); i ++){
			char curChar = str.charAt(i);
			if(!(curChar >= '0' && curChar <= '9')) {
				if(i == 0) return 0;
				else {
					str = str.substring(0, i);
					break;
				}
			}
		}
		//判断是否越界
		if(str.length() > 10 && sign == 1) return 2147483647;
		if(str.length() > 10 && sign == 0) return -2147483648;
		if(str.length() == 10 && str.compareTo("2147483647") >= 0 && sign == 1) return 2147483647;
		else if(str.length() == 10 && str.compareTo("2147483648") >= 0 && sign == 0) return -2147483648;
		
		int sum = 0;
		int power = 0;
		for(int i = str.length() - 1; i >= 0; i--, power++){
			sum += (str.charAt(i)-'0')*Math.pow(10, power);
		}
		if(sign == 0) sum = 0 - sum;
		
        return sum;
    }
	
	public static void main(String[] args) {
		//String str = null;
		//String str = "";
		//String str = "+";
		//String str = "-";
		//String str = "+1";
		//String str = "+12";
		//String str = "-1";
		//String str = "-12";
		//String str = "1";
		//String str = "12";
		//String str = "+-1";
		//String str = "010";
		//String str = "    010";
		//String str = " -0012a42";
		//String str = "-2147483648";
		//String str = "-2147483649";
		//String str = "23a8f";
		String str = " -11919730356x";
		
		StringToIntegerAtoi stia = new StringToIntegerAtoi();
		System.out.println(stia.atoi(str));
	}
}

你可能感兴趣的:(Integer)