[LeetCode] String to Integer (atoi)
Cùng tôi giải quyết 1 bài toán hay trên LeetCode.
Tiêu đề: String to Integer (atoi)
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: Whitespace: Ignore any leading whitespace (" "). Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present. Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. Rounding: If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then round the integer to remain in the range. Specifically, integers less than -2^31 should be rounded to -2^31, and integers greater than 2^31 - 1 should be rounded to 2^31 - 1. Return the integer as the final result.
Đây là cách tôi giải quyết bài toán:
Đây là mã code đầy đủ của tôi:
class Solution:
def myAtoi(self, s: str) -> int:
num = "" # Khởi tạo một chuỗi rỗng để xây dựng số
for i in s: # Lặp qua từng ký tự trong chuỗi đầu vào
if i == " " and num == "": # Bỏ qua các khoảng trắng ở đầu
continue
if i in ["-", "+"] and num == "": # Kiểm tra dấu ở đầu chuỗi
num = num + i # Thêm dấu vào chuỗi số
continue
if i.isnumeric(): # Nếu ký tự là chữ số
num = num + i # Thêm chữ số vào chuỗi số
if not i.isnumeric(): # Nếu ký tự không phải là chữ số
break # Dừng xử lý khi gặp ký tự không phải số
# Nếu không tìm thấy số hợp lệ, hoặc chỉ tìm thấy dấu, trả về 0
if num == "" or num == "+" or num == "-":
return 0
# Chuyển đổi chuỗi số thành số nguyên và xử lý tràn số
if int(num) < -2**31: # Kiểm tra tràn dưới
return -2**31
if int(num) > 2**31 - 1: # Kiểm tra tràn trên
return 2**31 - 1
return int(num) # Trả về số nguyên cuối cùng
Kết quả tôi nhận được khá tốt:
Cảm ơn bạn đã quan tâm đến bài viết của tôi. Hãy chia sẻ thuật toán của bạn với tôi nhé!
All rights reserved