Sum of digits
A non-negative integer N is given.
Print the sum of all its digits.
- Input
- 0 ≤ N ≤ 1,000,000,000
- Output
- sum of the digits
1234
10
A non-negative integer N is given.
Print the sum of all its digits.
1234
10
When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).
$ Ready
Open this on a computer to write and run code. On mobile you can read the problem and the solutions.
Two approaches: treat it as text and convert each character (Python sum(map(int, s)), C-family c - '0'), or treat it as a number, taking the last digit with % 10 and shrinking with / 10.
In Craykon and JS / is fractional, so you need Math.Floor (Math.floor).
s = input().strip()print(sum(map(int, s)))const s = require("fs").readFileSync(0, "utf8").trim();console.log([...s].reduce((t, c) => t + Number(c), 0));import { readFileSync } from "node:fs";const s: string = readFileSync(0, "utf8").trim();console.log([...s].reduce((t, c) => t + Number(c), 0));import java.util.Scanner; public class Main { public static void main(String[] args) { String s = new Scanner(System.in).next(); int total = 0; for (char c : s.toCharArray()) total += c - '0'; System.out.println(total); }}using System; class Program{ static void Main() { string s = Console.ReadLine().Trim(); int total = 0; foreach (char c in s) total += c - '0'; Console.WriteLine(total); }}#include <iostream>#include <string> int main() { std::string s; std::cin >> s; int total = 0; for (char c : s) total += c - '0'; std::cout << total << '\n';}#include <stdio.h> int main(void) { long long n; scanf("%lld", &n); int total = 0; do { total += n % 10; n /= 10; } while (n > 0); printf("%d\n", total); return 0;}n = Console.ReadLine().ToNumber();total = 0;while (n > 0){ total += n % 10; n = Mathf.Floor(n / 10);}Console.WriteLine(total);