Sum of Digits
Add up all the digits of a number.
Sample input
12345
Sample output
15
Solution
n = 12345
total = 0
while n > 0:
total += n % 10
n //= 10
print(total)
let n = 12345, total = 0;
while (n > 0) {
total += n % 10;
n = Math.floor(n / 10);
}
console.log(total);
public class Main {
public static void main(String[] args) {
int n = 12345, total = 0;
while (n > 0) {
total += n % 10;
n /= 10;
}
System.out.println(total);
}
}
fun main() {
var n = 12345
var total = 0
while (n > 0) {
total += n % 10
n /= 10
}
println(total)
}
var n = 12345
var total = 0
while n > 0 {
total += n % 10
n /= 10
}
print(total)
void main() {
int n = 12345, total = 0;
while (n > 0) {
total += n % 10;
n ~/= 10;
}
print(total);
}
#include <iostream>
using namespace std;
int main() {
int n = 12345, total = 0;
while (n > 0) {
total += n % 10;
n /= 10;
}
cout << total << endl;
return 0;
}
#include <stdio.h>
int main() {
int n = 12345, total = 0;
while (n > 0) {
total += n % 10;
n /= 10;
}
printf("%d\n", total);
return 0;
}