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
}
相关推荐
有泽改之_6 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
im_AMBER6 小时前
Leetcode 74 K 和数对的最大数目
数据结构·笔记·学习·算法·leetcode
长安er7 小时前
LeetCode 206/92/25 链表翻转问题-“盒子-标签-纸条模型”
java·数据结构·算法·leetcode·链表·链表翻转
Benmao⁢7 小时前
C语言期末复习笔记
c语言·开发语言·笔记·leetcode·面试·蓝桥杯
CoderYanger7 小时前
动态规划算法-01背包问题:50.分割等和子集
java·算法·leetcode·动态规划·1024程序员节
菜鸟233号9 小时前
力扣513 找树左下角的值 java实现
java·数据结构·算法·leetcode
leoufung9 小时前
LeetCode 22:Generate Parentheses 题解(DFS / 回溯)
算法·leetcode·深度优先
FMRbpm9 小时前
队列练习--------最近的请求次数(LeetCode 933)
数据结构·c++·leetcode·新手入门
长安er11 小时前
LeetCode 34排序数组中查找元素的第一个和最后一个位置-二分查找
数据结构·算法·leetcode·二分查找·力扣
CoderYanger11 小时前
动态规划算法-两个数组的dp(含字符串数组):48.最长重复子数组
java·算法·leetcode·动态规划·1024程序员节