How can I find how many useful digits are in any given a number N
Solution 1
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
Solution 2
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)
Jake Dobson
I am focusing on Swift, Objective-C, and Unity3D. I want to build killer apps/games that are easy to use, make every day a little better, and look great! I come from Seattle and the Midwest, where I played a ton of hockey as a kid. I love anything that I haven't done or seen before, except country music. ADD consumes my brain, try and keep up!
Updated on August 24, 2022Comments
-
Jake Dobson over 1 year
A digit in the number is useful if the number is divisible by that digit.
I have been working on this for 2 days now.
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'