반응형

https://leetcode.com/problems/largest-odd-number-in-string/

 

Largest Odd Number in String - LeetCode

Can you solve this real interview question? Largest Odd Number in String - You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd i

leetcode.com

 

가장 오른쪽 숫자부터 탐색하며, 홀수가 처음 나오는 지점까지의 substring이 가장 큰 홀수가 됩니다.

class Solution {
public:
    string largestOddNumber(string num) {
        for(int i=num.size() - 1; i>=0; i--) {
            if((num[i] - '0') % 2) {
                return num.substr(0, i + 1);
            }
        }
        return "";
    }
};
반응형

+ Recent posts