Created
October 18, 2019 15:03
-
-
Save balitax/d2ab71de06c0e0def3401a7c2d9cb9b1 to your computer and use it in GitHub Desktop.
Count a number into 1 digit value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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