-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1903-LargestOddNumberInString.go
More file actions
56 lines (47 loc) · 1.59 KB
/
1903-LargestOddNumberInString.go
File metadata and controls
56 lines (47 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
// 1903. 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 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 <= 10^5
// num only consists of digits and does not contain any leading zeros.
import "fmt"
func largestOddNumber(num string) string {
arr, i := []byte(num), len(num) - 1
for ; i >= 0; i-- {
if int(arr[i] - '0') % 2 == 1 { break }
}
if i == -1 { return "" }
return string(arr[:i + 1])
}
func main() {
// Example 1:
// Input: num = "52"
// Output: "5"
// Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number.
fmt.Println(largestOddNumber("52")) // "5"
// Example 2:
// Input: num = "4206"
// Output: ""
// Explanation: There are no odd numbers in "4206".
fmt.Println(largestOddNumber("4206")) // ""
// Example 3:
// Input: num = "35427"
// Output: "35427"
// Explanation: "35427" is already an odd number.
fmt.Println(largestOddNumber("35427")) // "35427"
}