
例如,如果我有数字 35565,则输出为 3565。
所以,我的代码片段得到了个位数,但我不知道如何保留前一个数字以与下一个数字进行检查。
for {
num = num / 10
fmt.Print(num)
if num/10 == 0 {
break
}
}这种方法从右到左将数字分解为数字,将它们存储为整数切片,然后从左到右迭代这些数字以构建具有“连续唯一”数字的数字。
我最初尝试从左到右分解数字,但不知道如何处理占位零;从右到左分解它,我知道如何捕获这些零。
国产著名网上商店系统,真正企业级应用软件,性能卓越,在国内外享有盛誉,用户遍布欧洲、美洲、大洋洲,支持多语言,前台与后台均可设置为不同语言界面,用户帮助文档极其丰富,PHP+MySQL+Zend运行环境,让你快速建立个性化的网上商店,内置几十种网上支付网关、内置数十套精美模板,支持实体、非实体商品销售。 更新功能调整: 1、应用中心:APP的“更新时间”字段
0
// 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中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号