{ }codelper
null valuesbooleansreading n linesP0047

Fill blanks with the last value

A thermometer recorded n readings in order, but when it failed to measure, a blank line was left.
The first line gives n, and each of the next n lines is either one integer or a blank line (a line with nothing on it, not even spaces).
For each line print one result line: the integer if there is one, or for a blank line the most recent integer recorded before it.
If no integer has been recorded yet, print "none".
Zero and negative numbers are recorded values too.

Input
1 ≤ n ≤ 1,000, -1,000 ≤ recorded value ≤ 1,000
Output
n lines, a number or "none"
Example 1 · stdin
5

3

0

stdout
none
3
3
0
0
Example 2 · stdin
3
-1


stdout
-1
-1
-1
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

How you hold "no value yet" differs by language.
Python None (check with last is None), JS null, TS number | null (in strict mode you cannot use it as a number before checking), Java cannot put null in an int, so use Integer (computing with a null one throws NullPointerException), C# int? (HasValue, ??), C++17 std::optional<int>, Craykon null.
C's int has no "nothing" at all, so keep a separate boolean such as bool has = false (<stdbool.h>).
Three traps: (1) standing in for "nothing" with a special number like 0 or -1 makes it impossible to tell from a real 0 or -1 (example 2).
(2) Asking with a truth test like if (last) / if last: treats 0 as false in JS and Python, so "none" appears after a 0 was read — ask whether it is null explicitly: last === null, last is None.
(3) A blank line is not null but the empty string "" (Craykon Console.ReadLine() also gives "" for a blank line and null only at the end of input).
Converting it straight to a number stops Python int("") with ValueError and Java Integer.parseInt("") with NumberFormatException, while JS Number("") and C atoi("") silently give 0.
So check for a blank line as text before converting.

Pythonmain.py · 7 lines
n = int(input())last = None                      # 아직 읽은 수가 없음for _ in range(n):    line = input()    if line != "":        last = int(line)    print("none" if last is None else last)
JavaScriptmain.js · 10 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);let last = null; // 아직 읽은 수가 없음const out = [];for (let i = 1; i <= n; i++) {  // Number("")는 0이라서 빈 줄인지 먼저 글자로 확인한다  if (lines[i] !== "") last = Number(lines[i]);  out.push(last === null ? "none" : last);}console.log(out.join("\n"));
TypeScriptmain.ts · 11 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const n: number = Number(lines[0]);let last: number | null = null; // 아직 읽은 수가 없음const out: string[] = [];for (let i = 1; i <= n; i++) {  // Number("")는 0이라서 빈 줄인지 먼저 글자로 확인한다  if (lines[i] !== "") last = Number(lines[i]);  out.push(last === null ? "none" : String(last));}console.log(out.join("\n"));
JavaMain.java · 18 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());        Integer last = null; // int는 null을 담을 수 없어 Integer를 쓴다        StringBuilder out = new StringBuilder();        for (int i = 0; i < n; i++) {            String line = in.readLine();            if (!line.isEmpty()) last = Integer.parseInt(line);            out.append(last == null ? "none" : last.toString()).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 19 lines
using System;using System.Text; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine());        int? last = null; // int? 는 null도 담는 int        var out_ = new StringBuilder();        for (int i = 0; i < n; i++)        {            string line = Console.ReadLine();            if (line != "") last = int.Parse(line);            out_.Append(last.HasValue ? last.Value.ToString() : "none").Append('\n');        }        Console.Write(out_);    }}
C++main.cpp · 16 lines
#include <iostream>#include <optional>#include <string> int main() {    std::string line;    std::getline(std::cin, line);    int n = std::stoi(line);    std::optional<int> last;  // 처음에는 값이 없음    for (int i = 0; i < n; i++) {        std::getline(std::cin, line);        if (!line.empty()) last = std::stoi(line);        if (last) std::cout << *last << '\n';        else std::cout << "none\n";    }}
Cmain.c · 22 lines
#include <stdbool.h>#include <stdio.h>#include <stdlib.h> int main(void) {    char line[32];    fgets(line, sizeof line, stdin);    int n = atoi(line);    /* C의 int에는 '값 없음'이 없어서 따로 참·거짓 하나를 둔다 */    bool has = false;    int last = 0;    for (int i = 0; i < n; i++) {        fgets(line, sizeof line, stdin);        if (line[0] != '\n' && line[0] != '\0') {            last = atoi(line);            has = true;        }        if (has) printf("%d\n", last);        else puts("none");    }    return 0;}
Craykonmain.cray · 18 lines
n = Console.ReadLine().ToNumber();마지막 = null;for (i = 0; i < n; i++){    줄 = Console.ReadLine();    if (줄 != "")    {        마지막 = 줄.ToNumber();    }    if (마지막 == null)    {        Console.WriteLine("none");    }    else    {        Console.WriteLine(마지막);    }}