Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- CHALLENGE
- Write a function called sumOfDigits that given an integer, returns the sum of its digits. If you need an extra challenge, find a solution that works without using Strings.
- Example
- sumOfDigits(23) // returns 5
- sumOfDigits(496) // returns 19
- ASSUMPTIONS
- 1. There will be no negative numbers
- 2. Will only be given integers
- TEST CASES
- sumOfDigits(23) // returns 5
- sumOfDigits(496) // returns 19
- sumOfDigits(402) // returns 6
- sumOfDigits(1) // returns 1
- CODING APPROACH
- Use compactMap to go through each item in the integer and put it into an array. Do a for-in loop to loop through all of the integers in the array and add them together.
- CODE
- func sumOfDigits(fullInt: Int) {
- let fullIntString = "\(fullInt)"
- let arrayOfDigits = fullIntString.map { Int(String($0))}
- for eachDigit in arrayOfDigits {
- let sum = sum + eachDigit
- }
- return sum
- }
- sumOfDigits(fullInt: 429)
Add Comment
Please, Sign In to add comment