2
1
paiza×Qiita記事投稿キャンペーン「プログラミング問題をやってみて書いたコードを投稿しよう!」

paizaラーニングレベルアップ問題集の「N倍の文字列」を色々な言語でやってみた

Last updated at Posted at 2024-08-13

paiza×Qiita記事投稿キャンペーンということで、paizaラーニングレベルアップ問題集のN倍の文字列を色々な言語でやってみました。対象はコードモンスター大図鑑で対応している9言語です。

2024/08/24追記
Perl, Scala, Go, Swiftの4言語を追加いたしました。

2024/08/25更新
Javascriptのコードを修正いたしました。
コメントいただき有難うございます。


方針
  • 整数$N$を受け取る
  • $N$個の*を繋げた文字列を生成する
  • 文字列を出力する

PHP
<?php
	$n = fgets(STDIN);
	$s = str_repeat("*", $n);
	echo $s."\n";
?>

Ruby
n = gets.to_i
s = "*" * n
puts s

Java
import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		sc.close();
		String s = "*".repeat(n);		
		System.out.println(s);
	}
}

Python
n = int(input())
s = "*" * n
print(s)

C言語

$N$回文字*を出力する

#include <stdio.h>

int main(void){
	int n;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		putchar('*');
	}
	puts("");
	return 0;
}

$N$個の*を繋げた文字列を生成する

#include <stdio.h>
#include <string.h>

int main(void){
	int n;
	scanf("%d", &n);
	char s[n + 1];
	memset(s, '*', n);
	s[n] = '\0';
	puts(s);
	return 0;
}

C#
using System;

class Program
{
	static void Main()
	{
		int n = int.Parse(Console.ReadLine());
		string s = new string('*', n);
		Console.WriteLine(s);
	}
}

Javascript
const lines = require("fs").readFileSync("/dev/stdin", "utf8").split("\n");
// 2024-08-25 parseIntからNumberに修正
// const n = parseInt(lines[0], 10);
const n = Number(lines[0]);
const s = "*".repeat(n);
console.log(s);

C++
#include <iostream>
using namespace std;

int main(void){
	int n;
	cin >> n;
	string s(n, '*');
	cout << s << endl;
	return 0;
}

Kotlin
import java.util.*

fun main() {
	val sc = Scanner(System.`in`)
	val n = sc.nextInt()
	sc.close()
	val s = "*".repeat(n)
	println(s)
}

Perl
$n = <STDIN>;
print '*' x $n, "\n";

Scala
import scala.io.StdIn._

object Main extends App {
	val n = readLine().toInt
	println("*" * n)
}

Go
package main
import (
    "fmt"
    "strings"
)
func main() {
	var n int
	fmt.Scan(&n)
	fmt.Println(strings.Repeat("*", n))
}

Swift
import Foundation

let n = Int(readLine()!)!
print(String(repeating:"*", count:n))
2
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1