3

A digit in the number is useful if the number is divisible by that digit.

Here is what I have:

func selfDivide(integer: Int) -> Int {
    var numString = String(integer)
    for character in numString.characters {
        if character % numString == 0 {
            return character
        }
    }
}

I'm thinking I have to find a way to use % between that string and character.

The error that I get is:

Binary operator '%' cannot be applied to characters of type 'Character' and 'String'

3
  • 3
    Put the code in your question instead of posting an image.
    – vacawama
    May 19, 2016 at 22:54
  • Edit your question. Cut and and paste the code into your question. Make sure there is a blank line above and below the code. The code should have 4 spaces minimum before each line. If it is on the right border, highlight all of the code and press the {} icon in the editor.
    – vacawama
    May 23, 2016 at 0:05
  • 1
    Thanks @vacawama I was extremely new to swift, stack overflow (and programming in general) just 2 months ago! You actually helped me get into a coding bootcamp. I now look at this and see how bad it is to use strings, characters, and ints. What a nightmare I created for myself! Jul 18, 2016 at 4:13

5 Answers 5

22

Here is more Swifty way using extension (Swift 4+):

public extension Int {
    /// returns number of digits in Int number
    public var digitCount: Int {
        get {
            return numberOfDigits(in: self)
        }
    }
    /// returns number of useful digits in Int number
    public var usefulDigitCount: Int {
        get {
            var count = 0
            for digitOrder in 0..<self.digitCount {
                /// get each order digit from self
                let digit = self % (Int(truncating: pow(10, digitOrder + 1) as NSDecimalNumber))
                    / Int(truncating: pow(10, digitOrder) as NSDecimalNumber)
                if isUseful(digit) { count += 1 }
            }
            return count
        }
    }

    // private recursive method for counting digits
    private func numberOfDigits(in number: Int) -> Int {
        if number < 10 && number >= 0 || number > -10 && number < 0 {
            return 1
        } else {
            return 1 + numberOfDigits(in: number/10)
        }
    }
    // returns true if digit is useful in respect to self
    private func isUseful(_ digit: Int) -> Bool {
        return (digit != 0) && (self % digit == 0)
    }
}

Usage:

print(333444.digitCount)
print(333444.usefulDigitCount)
5
  • Could you elaborate on the (in: ) portion? I'm not familiar! Jan 28, 2017 at 1:15
  • What exactly you did not understand? in is just an argument label, self is a object of type Int.
    – nCod3d
    Jan 28, 2017 at 16:48
  • Oh, I see. They have been doing this more in Swift 3 I think. The struggles of learning Swift from the beginning... Jan 29, 2017 at 20:47
  • This doesn't solve the original problem. @JakeDobson was counting the number of useful digits, not just the number of digits.
    – vacawama
    May 18, 2017 at 9:27
  • This crashes if it is passed infinity.
    – Greg
    Nov 19, 2018 at 18:18
7

I would recommend doing all of the work with Int instead of converting to String. You can use % 10 to get the digits and / 10 to remove the last digit.

func selfDivide(number: Int) -> Int {
    var num = number
    var count = 0
    while num != 0 {
        let digit = abs(num % 10)
        if digit != 0 && number % digit == 0 {
            count += 1
        }
        num = num / 10
    }
    return count
}

Same answer provided as an extension to Int:

extension Int {
    var usefulDigits: Int {
        var num = self
        var count = 0
        while num != 0 {
            let digit = abs(num % 10)
            if digit != 0 && self % digit == 0 {
                count += 1
            }
            num = num / 10
        }
        return count
    }
}

Examples:

print(100.usefulDigits)      // 1
print(123.usefulDigits)      // 2
print(222.usefulDigits)      // 3
print(299.usefulDigits)      // 0
print(Int.max.usefulDigits)  // 4
print(Int.min.usefulDigits)  // 7
3
  • this didn't seem to work...When I use my compiler it returns the right answer. When I run the code on the online compiler to submit the code (if correct), it says every case fails. May 29, 2016 at 0:46
  • and the teacher said he "modified" and "got it to work that way" so I'm not really sure what could be wrong.. May 29, 2016 at 1:05
  • Downvoter, if you give me a use case that fails I can investigate the problem. Thanks.
    – vacawama
    Jul 25, 2019 at 10:45
0

In a single iteration of the while loop, the function will calculate out the last digit of number and check whether the last digit of number if not equals to 0 as well as the number is divisible by the digit or not, if the result is true then the count is incremented by 1. The last line removes the last digit from the number. Same process is repeated until the number is greater than 0. At last the number of useful digits is returned finally.

extension Int {

func usefulNumCount() -> Int {
        var count = 0
        var num = abs(self)
        while num > 0 {
            let remainder = num % 10
            if remainder != 0 && self % remainder == 0 {
                count += 1
            }
            num = num / 10
        }
        return count
    }

}
2
  • Please provide some explanation to your answer
    – Sfili_81
    Jun 3, 2019 at 14:42
  • I have added the explanation to my answer by editing my answer. Please query if any confusion. Thank you. Jun 3, 2019 at 14:51
0

This only makes sense to me with unsigned integers.

Please let me know if you have further sense to knock into me; I tend to need it.

public extension UnsignedInteger {
  /// The digits that make up this number.
  /// - Parameter radix: The base the result will use.
  func digits(radix: Self = 10) -> [Self] {
    sequence(state: self) { quotient in
      guard quotient > 0
      else { return nil }

      let division = quotient.quotientAndRemainder(dividingBy: radix)
      quotient = division.quotient
      return division.remainder
    }
    .reversed()
  }

  func usefulDigitCount(radix: Self = 10) -> Int {
    digits(radix: radix).filter(isMultiple).count
  }
}
-1

In Swift 5

extension BinaryInteger {
  var digits: [Int] {
    return String(describing: self).compactMap { Int(String($0)) }
  }
}

extension Int {
  public var digitCount: Int {
   get {
    return self.digits.count
   }
  }
}

extension Int {
  var usefulDigits: Int {
    var count = 0
    for digit in self.digits {
        if digit != 0 && self % digit == 0 {
            count += 1
        }
    }
    return count
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.