Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,226 questions

56,128 answers

573 users

How to find the frequency of each digit (0–9) in a number with Swift

1 Answer

0 votes
/// Counts how many times each digit (0–9) appears in a given number
/// and prints the results.
func printDigitFrequency(of number: Int) {
    // Array of 10 zeros, index = digit, value = count
    var frequency = Array(repeating: 0, count: 10)
    
    // Convert number to a string so we can iterate over characters
    let digits = String(number)
    
    // Count each digit
    for char in digits {
        if let digit = char.wholeNumberValue {
            frequency[digit] += 1
        }
    }
    
    // Print each digit and its frequency
    for digit in 0...9 {
        print("Digit \(digit): \(frequency[digit]) times")
    }
}

// Usage:
printDigitFrequency(of: 120220340501)



/*
run:

Digit 0: 4 times
Digit 1: 2 times
Digit 2: 3 times
Digit 3: 1 times
Digit 4: 1 times
Digit 5: 1 times
Digit 6: 0 times
Digit 7: 0 times
Digit 8: 0 times
Digit 9: 0 times

*/

 



answered Jul 2 by avibootz
...