首页 > 后端开发 > Golang > 正文

如何打印与前面的数字不同的数字?

WBOY
发布: 2024-02-06 09:51:09
转载
968 人浏览过

如何打印与前面的数字不同的数字?

问题内容

例如,如果我有数字 35565,则输出为 3565。

所以,我的代码片段得到了个位数,但我不知道如何保留前一个数字以与下一个数字进行检查。

for {
num = num / 10
fmt.Print(num)
        
if num/10 == 0 {
    break
}
}
登录后复制


正确答案


这种方法从右到左将数字分解为数字,将它们存储为整数切片,然后从左到右迭代这些数字以构建具有“连续唯一”数字的数字。

我最初尝试从左到右分解数字,但不知道如何处理占位零;从右到左分解它,我知道如何捕获这些零。

// unique removes sequences of repeated digits from non-negative x,
// returning only "sequentially unique" digits:
// 12→12, 122→12, 1001→101, 35565→3565.
//
// Negative x yields -1.
func unique(x int) int {
    switch {
    case x < 0:
        return -1
    case x <= 10:
        return x
    }

    // -- Split x into its digits
    var (
        mag     int   // the magnitude of x
        nDigits int   // the number of digits in x
        digits  []int // the digits of x
    )

    mag = int(math.Floor(math.Log10(float64(x))))
    nDigits = mag + 1

    // work from right-to-left to preserve place-holding zeroes
    digits = make([]int, nDigits)
    for i := nDigits - 1; i >= 0; i-- {
        digits[i] = x % 10
        x /= 10
    }

    // -- Build new, "sequentially unique", x from left-to-right
    var prevDigit, newX int

    for _, digit := range digits {
        if digit != prevDigit {
            newX = newX*10 + digit
        }
        prevDigit = digit
    }

    return newX
}
登录后复制

这是一个go playground 进行测试

可以通过翻转开头的负号并在末尾恢复它来适应处理负数。

以上是如何打印与前面的数字不同的数字?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!