iOS Dev India
Learn
Roadmap
Skills
Swift DSA
Build
Studio
Sandbox
Tools
Agent Skills
Community
Communities
Events
Library
Articles
Resources
Jobs
Create Profile
Home
Learn
Roadmap
Skills
Swift DSA
Build
Studio
Sandbox
Tools
Agent Skills
Community
Communities
Events
Library
Articles
Resources
Jobs
Create Profile
Challenges
/
Digit Sum
·
Step 9/100 · Hello Arrays
← Flip Signs
Word Lengths →
Description
Hint
Digit Sum
L1
Easy
Arrays & Hashing
Concept
Grabbing the decimal digits of a number by repeatedly dividing by 10 is a classic loop.
n % 10
yields the last digit and
n / 10
drops it.
For a non-negative integer
n
, return the sum of its decimal digits. For
0
, return
0
.
Examples
▸
n = 123
→ 6
▸
n = 9009
→ 18
▸
n = 0
→ 0
Progressive Hints
Hint 1 · Nudge
Peel a number apart one digit at a time, starting from the back.
Hint 2 · Plan
Repeatedly take the last digit with n % 10 and add it to a running total, then chop that digit off with integer division by 10. Stop once n reaches 0.
Hint 3 · Approach
total = 0. While n > 0: total = total + (n % 10); n = n / 10 (integer division). Return total.
Reveal the next hint
All hints are out. Take a breath and give it a shot.
Swift
Java
Solution.swift
Tests.swift (Read Only)
Run
Output
// Run your code to see the output here.
Press
ESC
to close.
Start typing to search...