各位数字之和
给出一个非负整数 N。
输出 N 的各位数字之和。
- 输入
- 0 ≤ N ≤ 1,000,000,000
- 输出
- 各位数字之和
1234
10
给出一个非负整数 N。
输出 N 的各位数字之和。
1234
10
运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。
$ 就绪
请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。
两种方法:当作字符串逐个字符转成数字(Python sum(map(int, s)),C 系 c - '0'),或者当作数字,用 % 10 取末位、用 / 10 缩小。
Craykon 和 JS 的 / 会得到小数,需要 数学.向下取整(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 = 控制台.读行().转数字();total = 0;当 (n > 0){ total += n % 10; n = 数学.向下取整(n / 10);}控制台.输出(total);