各桁の和
0 以上の整数 N が与えられる。
N の各桁をすべて足した値を出力せよ。
- 入力
- 0 ≤ N ≤ 1,000,000,000
- 出力
- 各桁の和
1234
10
0 以上の整数 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);