当前位置: > > > > 打印所有唯一的数字组合的功能
来源:stackoverflow
2024-04-19 14:36:30
0浏览
收藏
Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《打印所有唯一的数字组合的功能》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
问题内容
我一直在尝试创建一个函数,打印 1 位数字(0、1、2、3、4、5、6、7、8、9、10)、2 位数字(10)的所有唯一数字组合, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 23, 24, 25, 26, 27, 28, 29, 30, 32, 34 … 89) 和 3 位数字 (012) , 013, 014, 015, 016, 017, 018, 019, 023, 024, 025 … 789),从 0 开始。
到目前为止,我已经写了这篇文章,并且一直在测试“if”和“for”的不同位置,但没有成功:
func ncombinations(x int) { if x == 3 { fmt.Print(a, b, c) } if x == 2 { fmt.Print(a, b) } if x == 3 { fmt.Print(a) } for a := 0; a < 10; a++ { for b := a + 1; b < 10; b++ { for c := b + 1; c < 10; c++ { } } } }
如何让它发挥作用并优化它?
正确答案
这里有一个简单但有效且易于理解的解决方案来解决您的问题:
package main import ( "fmt" "strconv" ) func main() { nCombinations(3) } func nCombinations(input int) { if input == 1 { for i := 0; i <= 9; i++ { fmt.Println(i) } } else if input == 2 { for i := 0; i <= 99; i++ { if i <= 9 { fmt.Println("0" + strconv.Itoa(i)) } else { fmt.Println(i) } } } else if input == 3 { for i := 0; i <= 999; i++ { if i <= 9 { fmt.Println("00" + strconv.Itoa(i)) } else if i <= 99 { fmt.Println("0" + strconv.Itoa(i)) } else { fmt.Println(i) } } } else { fmt.Println("out of range") } }
今天关于《打印所有唯一的数字组合的功能》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注公众号!