Golang | Leetcode Golang题解之第556题下一个更大元素III

题目:

题解:

Go 复制代码
func nextGreaterElement(n int) int {
    x, cnt := n, 1
    for ; x >= 10 && x/10%10 >= x%10; x /= 10 {
        cnt++
    }
    x /= 10
    if x == 0 {
        return -1
    }

    targetDigit := x % 10
    x2, cnt2 := n, 0
    for ; x2%10 <= targetDigit; x2 /= 10 {
        cnt2++
    }
    x += x2%10 - targetDigit // 把 x2%10 换到 targetDigit 上

    for i := 0; i < cnt; i++ { // 反转 n 末尾的 cnt 个数字拼到 x 后
        d := targetDigit
        if i != cnt2 {
            d = n % 10
        }
        if x > math.MaxInt32/10 || x == math.MaxInt32/10 && d > 7 {
            return -1
        }
        x = x*10 + d
        n /= 10
    }
    return x
}
相关推荐
pursuit_csdn1 小时前
LeetCode 1022. Sum of Root To Leaf Binary Numbers
算法·leetcode·深度优先
踩坑记录3 小时前
leetcode hot100 35. 搜索插入位置 medium 二分查找
leetcode
普通网友5 小时前
PHP语言的正则表达式
开发语言·后端·golang
-海绵东东-5 小时前
哈希表······················
算法·leetcode·散列表
菜鸡儿齐6 小时前
leetcode-全排列
算法·leetcode·深度优先
不想看见4047 小时前
Maximal Square 基本动态规划:二维--力扣101算法题解笔记
算法·leetcode·动态规划
夏乌_Wx7 小时前
LeetCode 160. 相交链表 | 三种解法吃透核心逻辑(哈希表 + 双指针 + 长度对齐)
leetcode·链表·哈希表
Hag_207 小时前
LeetCode Hot100 53.最大子数组和
数据结构·算法·leetcode
pursuit_csdn7 小时前
LeetCode 1461. Check If a String Contains All Binary Codes of Size K
算法·leetcode·职场和发展
Crazy________8 小时前
力扣113个mysql简单题解析(包含plus题目)
mysql·算法·leetcode·职场和发展