{ }codelper
counting downaccumulating64-bit integersP0173

A bank ledger with commas

Read a bank account's deposits and withdrawals and print the amounts and balances in a readable form. The first line gives the number of transactions n and the starting balance b, separated by one space. Each of the next n lines gives one transaction amount a.
A positive amount is a deposit, a negative one is a withdrawal, and 0 is a transaction with no amount. For each transaction add a to the balance, and print the amount of that transaction and the balance after adding it on one line, separated by one space. Write a number by taking its digits without the sign and inserting a comma (,) every three digits counting from the right end.
Never put a comma at the very front (e.g.
1234567 → 1,234,567, 123 → 123). For a negative number put - in front of the grouped digits. For an amount, put + in front if it is positive, and write just 0, with no sign, if it is 0. A balance of 0 or more has no sign.

Input
1 ≤ n ≤ 1000, −10^12 ≤ b ≤ 10^12, −10^9 ≤ a ≤ 10^9.
All numbers are integers
Output
n lines
Example 1 · stdin
4 1500000
-250000
1234
0
-2000000
stdout
-250,000 1,250,000
+1,234 1,251,234
0 1,251,234
-2,000,000 -748,766
Example 2 · stdin
2 -999
999
1000000000
stdout
+999 0
+1,000,000,000 1,000,000,000
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

Commas are counted from the right end, so a loop that walks backward from the last digit is natural (for (i = len - 1; i >= 0; i--), Python range(len(s) - 1, -1, -1), Craykon for (i = s.Length - 1; i >= 0; i -= 1) (반복)).
Grouping by three from the left turns 1234 into "123,4".
Remove the sign before grouping.
Grouping "-123456" as a whole counts - as a digit and gives "-,123,456".
The balance goes up to 2 trillion (1 trillion plus 1 billion a thousand times).
An int (about 2.1 billion) cannot even hold the starting balance, so use long long in C/C++ and long in Java/C#.
Python integers have no size limit, and numbers in JS/TS/Craykon are exact integers up to 2^53 (about 9 quadrillion), so they work as is.
Built-in formats exist but differ.
Python f"{v:,}" always uses commas.
Java String.format("%,d", v) and C# v.ToString("N0") follow the machine's locale, so a German locale prints 1.234 with a period.
JS/TS toLocaleString also follows the locale, so pass "en-US".
C/C++ have no standard format that inserts commas regardless of locale (C++20 std::format("{:L}", v) also follows the locale).
Putting + on a 0 amount is another common mistake.

Pythonmain.py · 26 lines
def group(v):    """0 이상인 v를 오른쪽부터 세 자리마다 쉼표로 끊는다."""    s = str(v)    out = ""    for i in range(len(s) - 1, -1, -1):  # 맨 오른쪽 숫자부터 거꾸로        out = s[i] + out        if (len(s) - i) % 3 == 0 and i > 0:  # 세 개를 붙였고 앞에 숫자가 더 있으면            out = "," + out    return out  def money(v, plus):    if v < 0:        return "-" + group(-v)  # 부호는 떼고 끊은 뒤 앞에 붙인다    if v > 0 and plus:        return "+" + group(v)    return group(v)  n, balance = map(int, input().split())lines = []for _ in range(n):    a = int(input())    balance += a  # 잔액에 차례로 쌓는다    lines.append(money(a, True) + " " + money(balance, False))print("\n".join(lines))
JavaScriptmain.js · 28 lines
const nums = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const n = nums[0];let balance = nums[1]; // 2조까지라 Number(2^53 미만)로 정확하다 // 0 이상인 v를 오른쪽부터 세 자리마다 쉼표로 끊는다function group(v) {  const s = String(v);  let out = "";  for (let i = s.length - 1; i >= 0; i--) {    out = s[i] + out;    if ((s.length - i) % 3 === 0 && i > 0) out = "," + out;  }  return out;} function money(v, plus) {  if (v < 0) return "-" + group(-v); // 부호는 떼고 끊은 뒤 앞에 붙인다  if (v > 0 && plus) return "+" + group(v);  return group(v);} const out = [];for (let k = 0; k < n; k++) {  const a = nums[2 + k];  balance += a;  out.push(money(a, true) + " " + money(balance, false));}console.log(out.join("\n"));
TypeScriptmain.ts · 29 lines
import { readFileSync } from "node:fs";const nums: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const n: number = nums[0];let balance: number = nums[1]; // 2조까지라 number(2^53 미만)로 정확하다 // 0 이상인 v를 오른쪽부터 세 자리마다 쉼표로 끊는다function group(v: number): string {  const s: string = String(v);  let out = "";  for (let i = s.length - 1; i >= 0; i--) {    out = s[i] + out;    if ((s.length - i) % 3 === 0 && i > 0) out = "," + out;  }  return out;} function money(v: number, plus: boolean): string {  if (v < 0) return "-" + group(-v); // 부호는 떼고 끊은 뒤 앞에 붙인다  if (v > 0 && plus) return "+" + group(v);  return group(v);} const out: string[] = [];for (let k = 0; k < n; k++) {  const a: number = nums[2 + k];  balance += a;  out.push(money(a, true) + " " + money(balance, false));}console.log(out.join("\n"));
JavaMain.java · 36 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class Main {    // 0 이상인 v를 오른쪽부터 세 자리마다 쉼표로 끊는다    static String group(long v) {        String s = Long.toString(v);        StringBuilder out = new StringBuilder();        for (int i = s.length() - 1; i >= 0; i--) {            out.append(s.charAt(i));            if ((s.length() - i) % 3 == 0 && i > 0) out.append(',');        }        return out.reverse().toString(); // 거꾸로 붙였으니 마지막에 뒤집는다    }     static String money(long v, boolean plus) {        if (v < 0) return "-" + group(-v); // 부호는 떼고 끊은 뒤 앞에 붙인다        if (v > 0 && plus) return "+" + group(v);        return group(v);    }     public static void main(String[] args) throws IOException {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        String[] first = br.readLine().trim().split("\\s+");        int n = Integer.parseInt(first[0]);        long balance = Long.parseLong(first[1]); // 1조를 넘으니 int가 아니라 long        StringBuilder out = new StringBuilder();        for (int k = 0; k < n; k++) {            long a = Long.parseLong(br.readLine().trim());            balance += a;            out.append(money(a, true)).append(' ').append(money(balance, false)).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 40 lines
using System;using System.Text; class Program{    // 0 이상인 v를 오른쪽부터 세 자리마다 쉼표로 끊는다    static string Group(long v)    {        string s = v.ToString();        var out_ = new StringBuilder();        for (int i = s.Length - 1; i >= 0; i--)        {            out_.Insert(0, s[i]);            if ((s.Length - i) % 3 == 0 && i > 0) out_.Insert(0, ',');        }        return out_.ToString();    }     static string Money(long v, bool plus)    {        if (v < 0) return "-" + Group(-v); // 부호는 떼고 끊은 뒤 앞에 붙인다        if (v > 0 && plus) return "+" + Group(v);        return Group(v);    }     static void Main()    {        string[] first = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);        int n = int.Parse(first[0]);        long balance = long.Parse(first[1]); // 1조를 넘으니 int가 아니라 long        var sb = new StringBuilder();        for (int k = 0; k < n; k++)        {            long a = long.Parse(Console.ReadLine().Trim());            balance += a;            sb.Append(Money(a, true)).Append(' ').Append(Money(balance, false)).Append('\n');        }        Console.Write(sb);    }}
C++main.cpp · 30 lines
#include <iostream>#include <string> // 0 이상인 v를 오른쪽부터 세 자리마다 쉼표로 끊는다std::string group(long long v) {    std::string s = std::to_string(v);    std::string out;    for (int i = static_cast<int>(s.size()) - 1; i >= 0; i--) {        out.insert(out.begin(), s[i]);        if ((static_cast<int>(s.size()) - i) % 3 == 0 && i > 0) out.insert(out.begin(), ',');    }    return out;} std::string money(long long v, bool plus) {    if (v < 0) return "-" + group(-v); // 부호는 떼고 끊은 뒤 앞에 붙인다    if (v > 0 && plus) return "+" + group(v);    return group(v);} int main() {    int n;    long long balance, a; // 1조를 넘으니 int가 아니라 long long    std::cin >> n >> balance;    for (int k = 0; k < n; k++) {        std::cin >> a;        balance += a;        std::cout << money(a, true) << ' ' << money(balance, false) << '\n';    }}
Cmain.c · 37 lines
#include <stdio.h> /* 0 이상인 v를 오른쪽부터 세 자리마다 쉼표로 끊어 buf 안 어딘가에 쓰고, 그 시작을 돌려준다 */static char *group(long long v, char *buf, int size) {    char *p = buf + size - 1;    *p = '\0';    int count = 0;    do { /* 맨 오른쪽 숫자부터 거꾸로 채운다 */        if (count > 0 && count % 3 == 0) *--p = ',';        *--p = (char)('0' + v % 10);        v /= 10;        count++;    } while (v > 0);    return p;} static void money(long long v, int plus) {    char buf[40];    if (v < 0) printf("-%s", group(-v, buf, sizeof buf)); /* 부호는 떼고 끊은 뒤 앞에 붙인다 */    else if (v > 0 && plus) printf("+%s", group(v, buf, sizeof buf));    else printf("%s", group(v, buf, sizeof buf));} int main(void) {    int n;    long long balance, a; /* 1조를 넘으니 int가 아니라 long long */    scanf("%d %lld", &n, &balance);    for (int k = 0; k < n; k++) {        scanf("%lld", &a);        balance += a;        money(a, 1);        putchar(' ');        money(balance, 0);        putchar('\n');    }    return 0;}
Craykonmain.cray · 38 lines
첫줄 = Console.ReadNumbers();n = 첫줄[0];잔액 = 첫줄[1]; // 2조까지라 크레이콘 수로 정확하다for (k = 0; k < n; k += 1){    a = Console.ReadLine().ToNumber();    잔액 += a;    Console.WriteLine(돈(a, true) + " " + 돈(잔액, false));} // 0 이상인 v를 오른쪽부터 세 자리마다 쉼표로 끊는다끊기(v){    s = "" + v;    결과 = "";    for (i = s.Length - 1; i >= 0; i -= 1)    {        결과 = s[i] + 결과;        if ((s.Length - i) % 3 == 0 && i > 0)        {            결과 = "," + 결과;        }    }    return 결과;} 돈(v, 더하기표){    if (v < 0)    {        return "-" + 끊기(-v); // 부호는 떼고 끊은 뒤 앞에 붙인다    }    if (v > 0 && 더하기표)    {        return "+" + 끊기(v);    }    return 끊기(v);}