王廷瑋|數位醫療|智慧醫療: 8. String to Integer (atoi) WFU

2024年7月2日 星期二

8. String to Integer (atoi)

8. String to Integer (atoi)


實作 myAtoi(string s) 函數,該函數將字串轉換為32位元有符號整數。

myAtoi(string s) 演算法如下:空白字元:忽略任何前導空白字元(" ")。
符號:通過檢查下一個字元是否為 '-' 或 '+' 來確定符號,如果都不是,則假定為正數。
轉換:讀取整數,跳過前導零,直到遇到非數字字元或字串結尾。如果未讀取到任何數字,則結果為 0。
四捨五入:如果整數超出32位元有符號整數範圍 [-2^31, 2^31 - 1],則將整數四捨五入以保持在該範圍內。具體而言,小於 -2^31 的整數應四捨五入為 -2^31,大於 2^31 - 1 的整數應四捨五入為 2^31 - 1。
返回:返回整數作為最終結果。


Python


class Solution:
def myAtoi(self, s: str) -> int:
# Initialize variables
i = 0
n = len(s)
result = 0
sign = 1
# Skip leading whitespaces
while i < n and s[i].isspace():
i += 1
# Check for sign
if i < n and (s[i] == '-' or s[i] == '+'):
sign = -1 if s[i] == '-' else 1
i += 1
# Convert digits to integer
while i < n and s[i].isdigit():
digit = int(s[i])
# Check for overflow and underflow before updating the result
if result > (2**31 - 1 - digit) // 10:
return -2**31 if sign == -1 else 2**31 - 1
result = result * 10 + digit
i += 1
# Apply the sign to the result
result *= sign
return result

16.47MB, 27ms


C++


#include <string>
#include <climits>

class Solution {
public:
int myAtoi(std::string s) {
int n = s.size();
int i = 0;
int sign = 1;
long result = 0;
// Skip leading whitespaces
while (i < n && s[i] == ' ') {
i++;
}
// Check for sign
if (i < n && (s[i] == '-' || s[i] == '+')) {
sign = (s[i] == '-') ? -1 : 1;
i++;
}
// Convert digits to integer
while (i < n && isdigit(s[i])) {
int digit = s[i] - '0';
result = result * 10 + digit;
// Check for overflow and underflow
if (sign == 1 && result > INT_MAX) return INT_MAX;
if (sign == -1 && -result < INT_MIN) return INT_MIN;
i++;
}
return static_cast<int>(result * sign);
}
};

8.13MB, 6ms


Javascript


/**
* @param {string} s
* @return {number}
*/
var myAtoi = function(s) {
let i = 0;
let n = s.length;
let sign = 1;
let result = 0;

// Skip leading whitespaces
while (i < n && s[i] === ' ') {
i++;
}

// Check for sign
if (i < n && (s[i] === '-' || s[i] === '+')) {
sign = (s[i] === '-') ? -1 : 1;
i++;
}

// Convert digits to integer
while (i < n && s[i] >= '0' && s[i] <= '9') {
let digit = s.charCodeAt(i) - '0'.charCodeAt(0);
// Check for overflow and underflow
if (result > Math.floor((2**31 - 1 - digit) / 10)) {
return sign === 1 ? 2**31 - 1 : -(2**31);
}
result = result * 10 + digit;
i++;
}

// Apply the sign to the result
result *= sign;

return result;
};

53.22MB, 75ms