How to sort the digits of a number in ascending order with Go

1 Answer

0 votes
package main

import (
	"fmt"
	"sort"
	"strconv"
)

func sortDigitsOfNumberAscending(num int) int {
	// Convert the number to a string
	numStr := strconv.Itoa(num)

	// Convert the string to a slice of runes
	digits := []rune(numStr)

	// Sort the slice of runes
	sort.Slice(digits, func(i, j int) bool {
		return digits[i] < digits[j]
	})

	// Convert the sorted slice to string
	sortedStr := string(digits)

	// Convert the string to integer
	sortedNumber, _ := strconv.Atoi(sortedStr)

	return sortedNumber
}

func main() {
	num := 94352

	sortedNumber := sortDigitsOfNumberAscending(num)

	fmt.Println("Sorted number:", sortedNumber)
}



/*
run:

Sorted number: 23459

*/

 



answered Aug 13, 2024 by avibootz

Related questions

1 answer 74 views
1 answer 68 views
1 answer 75 views
1 answer 131 views
...