자릿수의 합
음이 아닌 정수 N이 주어진다.
N의 각 자릿수를 모두 더한 값을 출력하라.
- 입력
- 0 ≤ N ≤ 1,000,000,000
- 출력
- 자릿수의 합
1234
10
음이 아닌 정수 N이 주어진다.
N의 각 자릿수를 모두 더한 값을 출력하라.
1234
10
실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).
$ 준비됐어요
코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.
두 가지 길: 글자로 보고 한 글자씩 수로 바꾸기(Python sum(map(int, s)), C 계열 c - '0'), 또는 수로 보고 % 10으로 끝자리를 떼고 / 10으로 줄이기.
크레이콘·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);