Skip to content

Latest commit

 

History

History
76 lines (61 loc) · 2.85 KB

8. String to integer.md

File metadata and controls

76 lines (61 loc) · 2.85 KB

##8. String to Integer (atoi)

  • Implement atoi to convert a string to an integer.

Requirements for atoi: The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.


这个题比较麻烦的就是在不看hint的情况想到这几种情况,但只要注意了这几种情况,就不会踩雷了。

我开始解题目的时候,想复杂了,以为 “; 0 123” 这一类的字符串,返回值,应该是“123”,或者 “- 123” 返回“123”, 但其实不是的,这两类情况返回值是0. 这样反而容易些,因为要求就很死,就是只允许空格 + 正负号 + 数字。 一旦出现除了正负号和数字之外的字符,返回值就是0; 一旦正负号出现,后面必须是数字。 数字一旦出现,后面也必须是数字。 这里扔几个testing cases,说明这点:

	@Test
public void test() {
	int s = result.myAtoi ("; 0 123");
	assertEquals (0, s); 
	int s2 = result.myAtoi ("0 123");
	assertEquals (0, s2); 
	int s3 = result.myAtoi ("- 123");
	assertEquals (0, s3); 
	int s4 = result.myAtoi ("1 23");
	assertEquals (1, s4); 
}

	/**
	 * cases to consider:
	 * 1. empty string
	 * 2. trim white spaces
 	* 3. neglect non-number characters
 	* 4. deal with "+/-" signs at the front of a number
 	* */

	public int myAtoi(String str){
		//empty string
		if (str.isEmpty()) return 0; 
		
		//deal with +/- signs
		int sign = 1, i = 0;
		while (str.charAt(i) ==' ')
			i++;

		if (str.charAt(i) == '+' || str.charAt(i) == '-'){
			sign = str.charAt(i) == '-'? -1:1;
			i++; 
		}
		
		//deal with non-numeric characters: compare them with the range: '0'~'9'
		//get the int value from the string
		double result = 0;
	    while (str.length() > i && str.charAt(i) >='0' && str.charAt(i) <='9'){
	    	result = result *10 +(str.charAt(i) -'0');
	    	i++;
	    	}
	    
	    result = result * sign; 
	    
	     //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;
	    }