How to check if an integer include specific digits x times in Go

3 Answers

0 votes
package main

import (
	"fmt"
	"strconv"
	"strings"
)

// Function to check if an integer includes a specific digit x times
func includesDigitXTimes(n int, digit rune, xtimes int) bool {
	// Convert the integer to a string
	str := strconv.Itoa(n)
	// Count the occurrences of the specific digit
	count := strings.Count(str, string(digit))
	// Check if the count matches x
	return count == xtimes
}

func main() {
	number := 7097175
	digit := '7'
	xtimes := 3

	if includesDigitXTimes(number, digit, xtimes) {
		fmt.Printf("The number %d includes the digit '%c' exactly %d times.\n", number, digit, xtimes)
	} else {
		fmt.Printf("The number %d does not include the digit '%c' exactly %d times.\n", number, digit, xtimes)
	}
}



/*
run:

The number 7097175 includes the digit '7' exactly 3 times.

*/

 



answered Apr 27, 2025 by avibootz
0 votes
package main

import (
    "fmt"
)

func integerIncludeDigitXTimes(n int, xtims int, digit int) bool {
    count := 0

    // Count occurrences of the digit in the number
    for n > 0 {
        if n%10 == digit {
            count++
        }
        n = n / 10 // Perform integer division
    }

    // Return true if count matches xtims
    return count == xtims
}

func main() {
    fmt.Println(integerIncludeDigitXTimes(7097175, 3, 7)) 
    fmt.Println(integerIncludeDigitXTimes(70975, 3, 7))   
}




/*
run:

true
false

*/

 



answered Apr 27, 2025 by avibootz
0 votes
package main
 
import (
    "fmt"
    "strconv"
    "strings"
)
 
// Function to check if an integer includes a specific digit x times
func includesDigitXTimes(n int, digit int, xtimes int) bool {
    // Convert the integer to a string
    str := strconv.Itoa(n)
    
    runedigit := rune(digit + 48)

    // Count the occurrences of the specific digit
    count := strings.Count(str, string(runedigit))
    // Check if the count matches x
    return count == xtimes
}
 
func main() {
    number := 7097175
    digit := 7
    xtimes := 3
 
    if includesDigitXTimes(number, digit, xtimes) {
        fmt.Printf("The number %d includes the digit %d exactly %d times.\n", number, digit, xtimes)
    } else {
        fmt.Printf("The number %d does not include the digit %d exactly %d times.\n", number, digit, xtimes)
    }
}

 
/*
run:
 
The number 7097175 includes the digit 7 exactly 3 times.
 
*/

 



answered Apr 27, 2025 by avibootz
...