{ }codelper
取余整数除法while 循环P0006

各位数字之和

给出一个非负整数 N。
输出 N 的各位数字之和。

输入
0 ≤ N ≤ 1,000,000,000
输出
各位数字之和
样例 1 · stdin
1234
stdout
10
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

两种方法:当作字符串逐个字符转成数字(Python sum(map(int, s)),C 系 c - '0'),或者当作数字,用 % 10 取末位、用 / 10 缩小。
Craykon 和 JS 的 / 会得到小数,需要 数学.向下取整(Math.floor)。

Pythonmain.py · 2 行
s = input().strip()print(sum(map(int, s)))
JavaScriptmain.js · 2 行
const s = require("fs").readFileSync(0, "utf8").trim();console.log([...s].reduce((t, c) => t + Number(c), 0));
TypeScriptmain.ts · 3 行
import { readFileSync } from "node:fs";const s: string = readFileSync(0, "utf8").trim();console.log([...s].reduce((t, c) => t + Number(c), 0));
JavaMain.java · 10 行
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);    }}
C#Main.cs · 12 行
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);    }}
C++main.cpp · 10 行
#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';}
Cmain.c · 13 行
#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;}
Craykonmain.cray · 8 行
n = 控制台.读行().转数字();total = 0;当 (n > 0){    total += n % 10;    n = 数学.向下取整(n / 10);}控制台.输出(total);