如果else函数具有相同的符号

huangapple go评论83阅读模式
英文:

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(&quot;1000000&quot;, 10)

  n2 := new(big.Int)
  n2.SetString(&quot;1000009&quot;, 10)

  one := big.NewInt(1)

  for i := n1; i.Cmp(n2) &lt; 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 &amp;&amp; it with the i.Cmp(n2) &lt; 0 condition:

numIdenticalSymbols := 4
//                            as you said &quot;keep count till there is only 4 identical symbols&quot;
for i := n1; i.Cmp(n2) &lt; 0 &amp;&amp; !containsNIdenticalSymbols(numIdenticalSymbols, i) ; i.Add(i, one) { ... }

huangapple
  • 本文由 发表于 2022年7月23日 04:36:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/73085817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定