Problem analysis of Golang maximum decrement number algorithm
- 2020-06-01 10:01:46
- OfStack
In this paper, the maximum decrement number algorithm of Golang is discussed by example. I will share it with you for your reference as follows:
Given a non-negative integer, find the maximum decrement number contained in the non-negative integer. The declination of a number is the sequence of adjacent digits from large to small.
For example: 95345323, the decreasing number is: 953,95,53,53,532,32, so the maximum decreasing number is 953.
If the input number is negative, return negative 1.
If you can't find the decrement, return negative 1.
Code implementation:
package huawei
import (
"fmt"
"sort"
"strconv"
)
func Test5Base() {
num := 431492
degressiveNums := getDegressiveNums(num)
max := -1
if len(degressiveNums) > 0 {
max = getMax(degressiveNums)
}
fmt.Println("max:", max)
}
// To obtain num All the decreasing Numbers
func getDegressiveNums(num int) []int {
if num < 0 {
return []int{-1}
}
degressiveNums := make([]int, 0)
numStr := strconv.Itoa(num)
length := len(numStr)
// Length of i The substring
for i := 2; i < length; i++ {
// from j Began to intercept
for j := 0; j < length-i+1; j++ {
// Interception of digital
n, err := strconv.Atoi(numStr[j : j+i])
checkError(err, "string to integer")
// Is a decreasing number
if isDegressive(n) {
degressiveNums = append(degressiveNums, n)
}
}
}
return degressiveNums
}
// Determine the digital num Is it a decreasing number
func isDegressive(num int) bool {
weishu := make([]int, 0)
for num >= 1 {
n := num % 10
weishu = append(weishu, n)
num /= 10
}
return sort.IntsAreSorted(weishu)
}
// To obtain 1 a slice The largest number in
func getMax(nums []int) int {
if len(nums) == 0 {
panic("empty slice.")
}
max := nums[0]
for i := 1; i < len(nums); i++ {
if nums[i] > max {
max = nums[i]
}
}
return max
}
I hope this article has been helpful to you in the programming of Go language.