Guest User

Untitled

a guest
Dec 10th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. CHALLENGE
  2.  
  3. 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.
  4.  
  5. Example
  6. sumOfDigits(23) // returns 5
  7. sumOfDigits(496) // returns 19
  8.  
  9.  
  10. ASSUMPTIONS
  11. 1. There will be no negative numbers
  12. 2. Will only be given integers
  13.  
  14.  
  15. TEST CASES
  16. sumOfDigits(23) // returns 5
  17. sumOfDigits(496) // returns 19
  18. sumOfDigits(402) // returns 6
  19. sumOfDigits(1) // returns 1
  20.  
  21.  
  22. CODING APPROACH
  23. 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.
  24.  
  25. CODE
  26.  
  27. func sumOfDigits(fullInt: Int) {
  28.  
  29. let fullIntString = "\(fullInt)"
  30.  
  31. let arrayOfDigits = fullIntString.map { Int(String($0))}
  32.  
  33. for eachDigit in arrayOfDigits {
  34. let sum = sum + eachDigit
  35. }
  36.  
  37. return sum
  38.  
  39. }
  40.  
  41. sumOfDigits(fullInt: 429)
Add Comment
Please, Sign In to add comment