尼瑪,我要被這道題的題目搞死了... 2016/10/12
編程語言是 Java,代碼托管在我的 GitHub 上,包括測試用例。歡迎各種批評(píng)指正!
<br />
題目 —— 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 os representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
<br >
解答
-
題目大意
實(shí)現(xiàn) atoi:將一個(gè)字符串轉(zhuǎn)化為整數(shù)。atoi 的要求(這個(gè)要求搞死我了。。。):
- 首先丟棄所有的空字符,直到找到第一個(gè)非空字符。然后,從這個(gè)字符開始,取出一個(gè)可選的初始正負(fù)號(hào)(正號(hào)或者負(fù)號(hào)),然后將剩下的部分轉(zhuǎn)化為數(shù)值。
- 這個(gè)字符串可能在構(gòu)成整數(shù)的所有數(shù)后面附加一些字符,我們直接忽視這些字符就好,也就是說,它們不會(huì)對(duì)我們這個(gè)函數(shù)產(chǎn)生影響。
- 如果這個(gè)字符串中的第一個(gè)非空字符串不是一個(gè)有效的數(shù)字,或者這樣的非空字符串不存在,則不會(huì)產(chǎn)生轉(zhuǎn)換為數(shù)字的行為。
- 如果沒有有效的轉(zhuǎn)換行為存在,那么就返回 0。如果即將返回的值溢出了,那么返回 INT_MAX 或者 INT_MIN。
-
解題思路
一個(gè)需求一個(gè)需求地實(shí)現(xiàn)。。。判斷溢出的時(shí)候稍微有點(diǎn)繞。- 注意這種把整數(shù)按位處理的一般就是 *10 或者 /10。
- 這里正負(fù)號(hào)處理的邏輯還是有點(diǎn)巧妙的,存到 sign 這個(gè)變量中,最后乘上結(jié)果。
代碼實(shí)現(xiàn)
public class Solution {
public int myAtoi(String str) {
if (str.length() == 0) return 0;
int i = 0, result = 0, sign = 1;
// 跳過空字符
while (i < str.length() && str.charAt(i) == ' ') {
i++;
}
// 獲取符號(hào)位
if (str.charAt(i) == '+' || str.charAt(i) == '-') {
sign = (str.charAt(i) == '+') ? 1 : -1;
i++;
}
// 判斷其他情況
while (i < str.length()) {
int digit = str.charAt(i) - '0';
if (digit < 0 || digit > 9) break;
if (Integer.MAX_VALUE/10 < result || Integer.MAX_VALUE/10 == result && Integer.MAX_VALUE % 10 < digit) {
return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
result = result * 10 + digit;
i++;
}
return result * sign;
}
}
-
小結(jié)
這個(gè)題目不難,但是太長太難讀了啊...讀了好幾遍才讀懂每一句的意思。不知道翻譯的你們能看懂不?記得判斷空串,然后就是處理符號(hào)位,要耐心、仔細(xì)。