Skip to content

Commit 286c02b

Browse files
committed
add sol
1 parent c70a673 commit 286c02b

File tree

1 file changed

+48
-0
lines changed
  • leetcode/179.LargestNumber

1 file changed

+48
-0
lines changed

leetcode/179.LargestNumber/sol.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// https://leetcode.com/problems/largest-number/description/
2+
3+
package main
4+
5+
import (
6+
"fmt"
7+
"sort"
8+
"strconv"
9+
"strings"
10+
)
11+
12+
// Custom comparator function
13+
func compare(x, y string) bool {
14+
return x+y > y+x
15+
}
16+
17+
func largestNumber(nums []int) string {
18+
// Convert numbers to string
19+
numsStr := make([]string, len(nums))
20+
for i, num := range nums {
21+
numsStr[i] = strconv.Itoa(num)
22+
}
23+
// fmt.Print(numsStr)
24+
25+
// Sort numbers using custom comparator
26+
sort.Slice(numsStr, func(i, j int) bool {
27+
return compare(numsStr[i], numsStr[j])
28+
})
29+
30+
// fmt.Print(numsStr)
31+
32+
// Join the sorted strings
33+
result := strings.Join(numsStr, "")
34+
35+
// Handle edge case where the result is "0" (e.g., when input is [0, 0])
36+
if result[0] == '0' {
37+
return "0"
38+
}
39+
40+
return result
41+
}
42+
43+
func main() {
44+
// Example usage
45+
nums := []int{3, 30, 34, 5, 9}
46+
result := largestNumber(nums)
47+
fmt.Println("Largest number:", result)
48+
}

0 commit comments

Comments
 (0)