英文:
If else function with identical symbols
问题
我有这个代码:
func main() {
n1 := new(big.Int)
n1.SetString("1000000", 10)
n2 := new(big.Int)
n2.SetString("1000009", 10)
one := big.NewInt(1)
for i := n1; i.Cmp(n2) < 0; i.Add(i, one) {
//fmt.Println(i)
}
}
我该如何使得当 n1 := 100000 < -- 有5个相同的数字或者122222等等时,只保留计数直到只有4个相同的数字(例如100001)...然后转到下一行。
我知道我需要使用... if ... else ... 但是我不知道如何检查结果 n1 中是否只有4个相同的数字。
有什么想法吗?
英文:
I have this:
func main() {
n1 := new(big.Int)
n1.SetString("1000000", 10)
n2 := new(big.Int)
n2.SetString("1000009", 10)
one := big.NewInt(1)
for i := n1; i.Cmp(n2) < 0; i.Add(i, one) {
//fmt.Println(i)
}
}
How do I make when n1 := 100000 <-- got 5 identical symbols or 122222 and etc just to keep count till there is only 4 identical symbols (example 100001) ... then go to next line.
I know I need to use ... if ... else ... but I have no idea how to check if there is only 4 identical symbols in result of n1
Any idea?
答案1
得分: 1
我不知道这是否完全符合你的意思,但我可以建议你创建一个函数,该函数接受一个 *big.Int
和一个特定数量的相同符号,并返回是否存在重复出现 n
次的字符:
func containsNIdenticalSymbols(n int, i *big.Int) bool {
counter := make(map[rune]int)
for _, char := range i.String() {
counter[char]++
}
hasNumIdenticalSymbols := false
for _, count := range counter {
if count == n {
hasNumIdenticalSymbols = true
break
}
}
return hasNumIdenticalSymbols
}
然后将其与 i.Cmp(n2) < 0
条件进行 &&
运算:
numIdenticalSymbols := 4
// 根据你说的 "keep count till there is only 4 identical symbols"
for i := n1; i.Cmp(n2) < 0 && !containsNIdenticalSymbols(numIdenticalSymbols, i); i.Add(i, one) { ... }
请注意,我已经将 HTML 实体字符进行了转义,以便在文本中显示。
英文:
I don't know if this is exactly what you mean or not, but I can suggest you create a function which accepts a *big.Int
and a specific number of identical symbols, and returns weather or not there's a character that is repeated n
times:
func containsNIdenticalSymbols(n int, i *big.Int) bool {
counter := make(map[rune]int)
for _, char := range i.String() {
counter[char] ++
}
hasNumIdenticalSymbols := false
for _, count := range counter {
if count == n { hasNumIdenticalSymbols = true; break }
}
return hasNumIdenticalSymbols
}
And just &&
it with the i.Cmp(n2) < 0
condition:
numIdenticalSymbols := 4
// as you said "keep count till there is only 4 identical symbols"
for i := n1; i.Cmp(n2) < 0 && !containsNIdenticalSymbols(numIdenticalSymbols, i) ; i.Add(i, one) { ... }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论