Solving Leetcode Interviews in Seconds with AI: Remove Trailing Zeros From a String
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2710" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given a positive integer num represented as a string, return the integer num without trailing zeros as a string. Example 1: Input: num = "51230100" Output: "512301" Explanation: Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301". Example 2: Input: num = "123" Output: "123" Explanation: Integer "123" has no trailing zeros, we return integer "123". Constraints: 1 <= num.length <= 1000 num consists of only digits. num doesn't have any leading zeros.
Explanation
- Iterate from the right: Start from the end of the string and move towards the beginning.
- Find the last non-zero character: Identify the index of the last character that is not '0'.
- Return the substring: Extract the substring from the beginning of the string up to (and including) the last non-zero character.
- Runtime Complexity: O(n), where n is the length of the input string. Storage Complexity: O(1) (excluding the output string).
Code
def remove_trailing_zeros(num: str) -> str:
"""
Given a positive integer num represented as a string, return the integer num without trailing zeros as a string.
For example:
remove_trailing_zeros("51230100") == "512301"
remove_trailing_zeros("123") == "123"
"""
i = len(num) - 1
while i >= 0 and num[i] == '0':
i -= 1
return num[:i + 1]