程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [leetcode]String to Integer (atoi)

[leetcode]String to Integer (atoi)

編輯:C++入門知識

[leetcode]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.


思路:

實現字符串轉換為int型整數並不難,只是有好多中輸入情況需要考慮,容易造成遺漏。首先看一下c++ 中atoi的定義:

-----------------------------------

atoi

int atoi (const char * str);
Convert string to integer Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.

The function first discards as many whitespace characters (as in isspace) 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 base-10 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 and zero is returned.


Return Value

On success, the function returns the converted integral number as an int value.
If the converted value would be out of the range of representable values by an int, it causes undefined behavior. See strtol for a more robust cross-platform alternative when this is a possibility.

------------------------------------------

可以看出需要注意的有以下幾點:

去掉前面的空格注意開始時候的符號 + -忽略數字後面的雜七雜八字符考慮溢出的情況。

考慮了上面幾方面,代碼就可以AC了。


代碼:

public class String_To_Integer { //java
	public static int atoi(String str) {
		int haveMinus = 1;
		long result = 0;  
		
		if(str == null || str.trim().isEmpty())
			return 0;
		
		//chech + - 
		str = str.trim();
		if(str.charAt(0) == '-'){
			str = str.substring(1);
			haveMinus = -1;
		}else if(str.charAt(0) == '+')
			str = str.substring(1);
		
		//check num
		for(int i = 0;i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'; i++){
			result = result*10 + (str.charAt(i)- '0');
		}
		
		//deal overflow
		if(result > 2147483647 && haveMinus == 1)
			return 2147483647;
		if(result > 2147483647 && haveMinus == -1)
			return -2147483648;
		
		return haveMinus*(int)result;
    }
	
	public static void main(String [] args){
		System.out.println(String_To_Integer.atoi("2147483648"));
	}
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved