class Solution:
def largestOddNumber(self, num: str) -> str:
# Start from the rightmost digit and move left
for i in range(len(num) - 1, -1, -1):
if int(num[i]) % 2 == 1:
return num[:i+1]
return ""
class Solution {
public:
string largestOddNumber(string num) {
for (int i = num.size() - 1; i >= 0; --i) {
if ((num[i] - '0') % 2 == 1) {
return num.substr(0, i + 1);
}
}
return "";
}
};
class Solution {
public String largestOddNumber(String num) {
for (int i = num.length() - 1; i >= 0; --i) {
if ((num.charAt(i) - '0') % 2 == 1) {
return num.substring(0, i + 1);
}
}
return "";
}
}
var largestOddNumber = function(num) {
for (let i = num.length - 1; i >= 0; --i) {
if (parseInt(num[i]) % 2 === 1) {
return num.slice(0, i + 1);
}
}
return "";
};
Given a string num
representing a large non-negative integer, you are asked to find the largest-valued odd integer (as a substring) that is a non-empty prefix of num
. In other words, you should return the longest prefix of num
that forms an odd number. If no such odd-valued prefix exists, return an empty string ""
.
num
is a digit ('0'-'9').
At first glance, you might consider checking every possible prefix of num
to see if it forms an odd number, but this could be inefficient for long strings. Instead, notice that the only thing that determines if a number is odd is its last digit. Therefore, to find the largest odd prefix, you only need to look for the rightmost odd digit in the string. Once you find it, the prefix ending at that digit is the answer.
This insight allows us to avoid generating all possible prefixes or doing any unnecessary calculations. We can simply scan the string backwards, checking each digit, and as soon as we find an odd digit, we return the prefix up to that point.
Let's break down the solution step by step:
This approach is efficient because it only requires a single pass through the string, and it does not require any extra data structures.
Let's use the input num = "35420"
as an example.
"3545"
, but since '5' is at index 1 (0-based), the prefix is "354"
. Wait, let's double-check: the prefix should include up to index 3, so the substring is num[:4]
which is "3542". But '2' is not odd; the correct index is 1 (0-based), so the prefix is num[:2]
which is "35". But let's clarify:
num[:2]
which is "35""35"
.
""
.
num
.
The key insight for solving the "Largest Odd Number in String" problem is recognizing that whether a number is odd depends only on its last digit. By scanning the string from right to left and looking for the rightmost odd digit, we can efficiently find the largest odd prefix in a single pass. This makes the solution both simple and optimal, requiring only O(N) time and O(1) extra space.