Skip to content

Instantly share code, notes, and snippets.

@balitax
Created October 18, 2019 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balitax/d2ab71de06c0e0def3401a7c2d9cb9b1 to your computer and use it in GitHub Desktop.
Save balitax/d2ab71de06c0e0def3401a7c2d9cb9b1 to your computer and use it in GitHub Desktop.
Count a number into 1 digit value
import Foundation
import UIKit
var number = 55555
// means 5+5+5+5+5 = 30 , so 3+0 = 3
func countDigits(_ digit: Int) -> Int {
var nums = digit
if nums < 0 {
nums = abs(nums)
}
var arrayInt = [Int]()
arrayInt.append(nums % 10)
while nums >= 10 {
nums = nums / 10
arrayInt.insert(nums % 10, at: 0)
}
var total = 0
for n in arrayInt {
total += n
}
if total > 9 {
return countDigits(total)
} else {
return total
}
}
print("TOTAL INTO 1 DIGIT = ", countDigits(number))
// -- TOTAL INTO 1 DIGIT = 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment