Algorithm Basics: Maximum decrement number problem (Golang implementation)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Give a non-negative integer to find the maximum number of decrements that is included in this nonnegative integer. The descending number of a number refers to the number of contiguous digits ranging from large to small.
such as: 95345323, the decrement number has: 953,95,53,53,532,32, then the largest decrement number is 953.
Assuming that the number entered is negative, return-1.
If you cannot find a decrement number, you also return-1.

Code implementation:

Package Huaweiimport ("FMT" "Sort" "StrConv") func test5base () {num: = 431492degressiveNums: = getdegressivenums (num) Max: = -1if len (degressivenums) > 0 {max = Getmax (degressivenums)}fmt. Println ("Max:", max)}//gets the total number of decrements of num func getdegressivenums (num int) []int {if num < 0 {return []int{-1}}degressivenums]: = Make ([]int, 0) Numstr: = StrConv. Itoa (num) Length: = Len (numstr)//String length of I for I: = 2; i < length; i++ {//from J Start intercept for J: = 0; J < length-i+1; J + + {//intercept number n, err: = StrConv. Atoi (Numstr[j:j+i]) checkerror (err, "string to Integer")//is the number of decrements if Isdegressive (n) {degressivenums = append ( Degressivenums, N)}}}return degressivenums}//infers whether the number num is a decrement number func isdegressive (num int) bool {Weishu: = make ([]int, 0) for Num >= 1 {n: = num% 10weishu = append (Weishu, n) Num/= 10}return sort. Intsaresorted (Weishu)}//gets the largest number of Func Getmax in a slice (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}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.