{ }codelper
additioncharactersP0421

The carry line of a column-addition key

You are making the answer key for an addition worksheet.
Besides the sum of the column addition, the key also shows the small carried digit at every place.
The first line gives the number of values to add, n.
Each of the next n lines gives one non-negative integer.
Each value is written with digits only, and a value other than 0 never starts with the digit 0.
In column addition all values are lined up at their right end (the ones place), and the places are added one at a time from the ones place to the left.
At each place, add all the digits in that place (a value with no digit there counts as 0) plus the value carried in from the place to its right; call this t.
The value carried into the ones place is 0.
Write t mod 10 (the remainder of t divided by 10) as the sum's digit at that place, and carry the quotient of t divided by 10 into the place directly to the left.
Keep going to the left while some value still has a digit there or the carried value is not 0.
When neither holds, stop.
Because n ≤ 10, a carried value is always a single digit from 0 to 9.
Print the carry line on the first line and the sum on the second line.
The sum is written with digits only; it is the single digit 0 only when the sum is 0, and otherwise it never starts with 0.
The carry line is a string as long as the sum.
Each character of the carry line is the value carried into the place of the sum directly below it; where that value is 0, write a period (.).
So the rightmost character of the carry line is always a period.

Input
2 ≤ n ≤ 10, each value has 1 to 1,000 digits (digits only), a value other than 0 does not start with 0
Output
Line 1: the carry line (as long as the sum, .
where the carried value is 0).
Line 2: the sum
Example 1 · stdin
3
487
59
6
stdout
12.
552
Example 2 · stdin
4
9999
999
99
9
stdout
1233.
11106
main.py
Input (stdin)

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.

In other languagesShow solutions by language · 8 languages

This problem takes all 8 languages.
The values have up to 1,000 digits, so no language adds them as whole numbers: like column addition at school, every solution turns each character into a digit and adds place by place.
Trap one: the values do not fit in the built-in integers.
long long in C and C++ and long in Java and C# hold only up to about 9.2 × 10^18 (19 digits), unsigned long long up to about 1.8 × 10^19 (20 digits), and JS/TS Number and Craykon numbers are doubles, so past 2^53 (about 9.0 × 10^15) the last digits can go wrong.
Adding with Number(s) in JS turns a 1,000-digit value into more than 1e308 and prints Infinity.
Python int, Java BigInteger, C# System.Numerics.BigInteger and JS/TS BigInt give a big sum exactly, but not the carry line, so you still need the place-by-place addition.
Trap two: turning a character into a number.
In JS and TS s[i] is the string "7", so t += s[i] joins instead of adding and grows like 0 + "7" + "9" → "079" (the solution converts with Number(...)).
In TS, adding a string into let t: number is stopped by the type check with TS2322.
In C, C++, Java and C#, s[i] (Java charAt) is a character code, so '7' is added as 55.
Subtract '0' to get 7.
In Craykon, number + string joins strings, so t becomes a string and the next t % 10 stops with an error saying % works only on numbers.
Convert with s[i].ToNumber().
In Python, t += s[i] stops at once with an int + str TypeError, so write int(s[i]).
Trap three: a carry can be larger than 1.
With three or more values the digits of one place can add up past 20.
The ones place of example 1 is 7 + 9 + 6 = 22, so 2 is carried.
Carrying 1 whenever t >= 10 prints "11." and 542.
Carry the quotient (t / 10, Python t // 10, JS Math.floor(t / 10), Craykon Mathf.Quot(t, 10)).
Trap four: the carry line shows the value carried into each place.
Writing the value carried out of a place above that place shifts everything by one, so example 1 gives ".12" instead of "12.".
Trap five: the last carry on the left.
Looping only over the places of the longest value loses the final carried 1 in example 2, printing "233." and 1106 instead of "1233." and 11106.
Keep going for one more place while a carry remains.
Trap six: places line up at the right end.
Reading values of different lengths from the left as s[col] puts the 4 of 487 and the 5 of 59 in the same place, and example 1 becomes 885.
The solutions read the place counted from the end, as in s[len(s) - 1 - col].
The solutions collect digits from the ones place and reverse them to print (Python reversed, JS/TS reverse(), Java StringBuilder.reverse(), C++ std::reverse, C# Array.Reverse; C prints from the back).
The Craykon solution puts each new place in front of the string.

Pythonmain.py · 21 lines
n = int(input())nums = [input().strip() for _ in range(n)]width = max(len(s) for s in nums) digits = []  # 합의 숫자, 일의 자리부터carries = []  # 그 자리로 받아올린 수, 일의 자리부터carry = 0col = 0while col < width or carry > 0:    t = carry    for s in nums:        if col < len(s):            # 오른쪽 끝에서 col번째 글자. 글자 '7'을 수 7로 바꾼다            t += int(s[len(s) - 1 - col])    carries.append(carry)    digits.append(t % 10)    carry = t // 10    col += 1 print("".join("." if c == 0 else str(c) for c in reversed(carries)))print("".join(str(d) for d in reversed(digits)))
JavaScriptmain.js · 20 lines
const [first, ...rest] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);const nums = rest.slice(0, Number(first));const width = Math.max(...nums.map((s) => s.length)); const digits = []; // 합의 숫자, 일의 자리부터const carries = []; // 그 자리로 받아올린 수, 일의 자리부터let carry = 0;for (let col = 0; col < width || carry > 0; col++) {  let t = carry;  for (const s of nums) {    // 글자 "7"은 문자열이라 그대로 더하면 이어 붙는다: Number로 바꾼다    if (col < s.length) t += Number(s[s.length - 1 - col]);  }  carries.push(carry);  digits.push(t % 10);  carry = Math.floor(t / 10);} console.log(carries.reverse().map((c) => (c === 0 ? "." : String(c))).join(""));console.log(digits.reverse().join(""));
TypeScriptmain.ts · 21 lines
import { readFileSync } from "node:fs";const [first, ...rest]: string[] = readFileSync(0, "utf8").trim().split(/\s+/);const nums: string[] = rest.slice(0, Number(first));const width: number = Math.max(...nums.map((s) => s.length)); const digits: number[] = []; // 합의 숫자, 일의 자리부터const carries: number[] = []; // 그 자리로 받아올린 수, 일의 자리부터let carry: number = 0;for (let col = 0; col < width || carry > 0; col++) {  let t: number = carry;  for (const s of nums) {    // 글자 "7"은 문자열이라 그대로 더하면 이어 붙는다: Number로 바꾼다    if (col < s.length) t += Number(s[s.length - 1 - col]);  }  carries.push(carry);  digits.push(t % 10);  carry = Math.floor(t / 10);} console.log(carries.reverse().map((c) => (c === 0 ? "." : String(c))).join(""));console.log(digits.reverse().join(""));
JavaMain.java · 33 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(in.readLine().trim());        String[] nums = new String[n];        int width = 0;        for (int i = 0; i < n; i++) {            nums[i] = in.readLine().trim();            width = Math.max(width, nums[i].length());        }         // 왼쪽 자리부터 찍어야 하므로 일의 자리부터 만들고 마지막에 뒤집는다        StringBuilder carryRow = new StringBuilder();        StringBuilder sum = new StringBuilder();        int carry = 0;        for (int col = 0; col < width || carry > 0; col++) {            int t = carry;            for (String s : nums) {                // char '7'은 코드 55이다: '0'을 빼야 수 7이 된다                if (col < s.length()) t += s.charAt(s.length() - 1 - col) - '0';            }            carryRow.append(carry == 0 ? '.' : (char) ('0' + carry));            sum.append((char) ('0' + t % 10));            carry = t / 10;        }        System.out.println(carryRow.reverse());        System.out.println(sum.reverse());    }}
C#Main.cs · 43 lines
using System;using System.Text; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine());        string[] nums = new string[n];        int width = 0;        for (int i = 0; i < n; i++)        {            nums[i] = Console.ReadLine().Trim();            width = Math.Max(width, nums[i].Length);        }         // 일의 자리부터 만들고, 찍을 때 거꾸로 읽는다        var carryRow = new StringBuilder();        var sum = new StringBuilder();        int carry = 0;        for (int col = 0; col < width || carry > 0; col++)        {            int t = carry;            foreach (string s in nums)            {                // char '7'은 코드 55이다: '0'을 빼야 수 7이 된다                if (col < s.Length) t += s[s.Length - 1 - col] - '0';            }            carryRow.Append(carry == 0 ? '.' : (char)('0' + carry));            sum.Append((char)('0' + t % 10));            carry = t / 10;        }        Console.WriteLine(Reverse(carryRow));        Console.WriteLine(Reverse(sum));    }     static string Reverse(StringBuilder sb)    {        char[] a = sb.ToString().ToCharArray();        Array.Reverse(a);        return new string(a);    }}
C++main.cpp · 32 lines
#include <algorithm>#include <iostream>#include <string>#include <vector> int main() {    int n;    std::cin >> n;    std::vector<std::string> nums(n);    std::size_t width = 0;    for (auto& s : nums) {        std::cin >> s;        width = std::max(width, s.size());    }     // 일의 자리부터 만들고 마지막에 뒤집는다    std::string carryRow, sum;    int carry = 0;    for (std::size_t col = 0; col < width || carry > 0; col++) {        int t = carry;        for (const auto& s : nums) {            // char '7'은 코드 55이다: '0'을 빼야 수 7이 된다            if (col < s.size()) t += s[s.size() - 1 - col] - '0';        }        carryRow += carry == 0 ? '.' : static_cast<char>('0' + carry);        sum += static_cast<char>('0' + t % 10);        carry = t / 10;    }    std::reverse(carryRow.begin(), carryRow.end());    std::reverse(sum.begin(), sum.end());    std::cout << carryRow << '\n' << sum << '\n';}
Cmain.c · 38 lines
#include <stdio.h>#include <string.h> #define LEN_MAX 1000#define N_MAX 10 char nums[N_MAX][LEN_MAX + 2];int lens[N_MAX];char carry_row[LEN_MAX + 3];char sum[LEN_MAX + 3]; int main(void) {    int n, width = 0;    scanf("%d", &n);    for (int i = 0; i < n; i++) {        scanf("%1001s", nums[i]);        lens[i] = (int)strlen(nums[i]);        if (lens[i] > width) width = lens[i];    }     /* 일의 자리부터 채우고, 찍을 때 거꾸로 찍는다 */    int carry = 0, col = 0;    for (; col < width || carry > 0; col++) {        int t = carry;        for (int i = 0; i < n; i++) {            /* char '7'은 코드 55이다: '0'을 빼야 수 7이 된다 */            if (col < lens[i]) t += nums[i][lens[i] - 1 - col] - '0';        }        carry_row[col] = carry == 0 ? '.' : (char)('0' + carry);        sum[col] = (char)('0' + t % 10);        carry = t / 10;    }    for (int i = col - 1; i >= 0; i--) putchar(carry_row[i]);    putchar('\n');    for (int i = col - 1; i >= 0; i--) putchar(sum[i]);    putchar('\n');    return 0;}
Craykonmain.cray · 40 lines
n = Console.ReadLine().ToNumber();nums = [];width = 0;for (i = 0; i < n; i++){    s = Console.ReadLine().Trim();    nums.Add(s);    width = Mathf.Max(width, s.Length);} // 왼쪽 자리부터 찍어야 하므로 새 자리를 문자열 앞에 붙여 간다carryRow = "";sum = "";carry = 0;col = 0;while (col < width || carry > 0){    t = carry;    foreach (s in nums)    {        if (col < s.Length)        {            // s[...]는 문자열 "7"이다: 수로변환 해야 수 7이 된다            t += s[s.Length - 1 - col].ToNumber();        }    }    if (carry == 0)    {        carryRow = "." + carryRow;    }    else    {        carryRow = carry + carryRow;    }    sum = t % 10 + sum;    carry = Mathf.Quot(t, 10);    col += 1;}Console.WriteLine(carryRow);Console.WriteLine(sum);