1.문제
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 integer exists.
A substring is a contiguous sequence of characters within a string.
숫자 문자열이 주어질 때 문자열의 부분 문자열중 가장 큰 홀수 부분 문자열을 리턴하는 문제이다.
Example 1
Input: num = "52"
Output: "5"
Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number.
Example 2
Input: num = "4206"
Output: ""
Explanation: There are no odd numbers in "4206".
Example 3
Input: num = "35427"
Output: "35427"
Explanation: "35427" is already an odd number.
Constraints:
- 1 <= num.length <= 105
- num only consists of digits and does not contain any leading zeros.
2.풀이
- 문자열의 앞에서 부터 1단어부터 ~ nums.length 단어 길이만큼 부분 문자열을 자른다.
- 자른 부분 문자열의 1의 자리를 이용하여 부분문자열이 홀수이고, 현재 answer보다 큰 값이라면 새로운 answer값으로 할당한다.
/**
* @param {string} num
* @return {string}
*/
const largestOddNumber = function (num) {
let sub = "";
let answer = "";
for (let i = 0; i <= num.length; i++) {
sub = num.substring(0, i); // index 0~i 까지의 부분 문자열
if (sub[sub.length - 1] % 2 !== 0 && answer < sub) { // 부분문자열이 홀수이고 현재 answer보다 큰값이라면 새로운 answer로 할당
answer = sub;
}
}
return answer;
};
3.결과
