1
0

【Ruby】paizaラーニング問題集解答(3けたごとにカンマ区切りで出力)

Posted at

大きな数値を 3 けたごとにカンマ区切りで出力 (paizaランク C 相当)

自分の解答

(分かりませんでした)

ChatGPTの解答

# 入力を受け取る
n = gets.chomp

# カンマ区切りで出力するための変数
output = ""

# 数値を3けたごとにカンマ区切りで出力する
(n.length / 3).times do |i|
  # 3けたごとの部分文字列を取得し、カンマを付けてoutputに追加
  output += "#{n[-3*(i+1), 3]},"
end

# 末尾のカンマを除去して出力
puts output.chomp(',')

このコードでは、まず与えられた数値Nを3桁ごとに区切ってカンマを付け、その後、末尾のカンマを除去して出力します。

自分の再解答

上記のChatGPTの解答では、以下のような入力と出力となる。

入力
111222333
出力
333,222,111

そのため、以下のように修正した。

practice.rb
# 入力の受け取り
input = gets.chomp.to_s

# 出力用変数の定義
output = ""

# 出力用変数に3桁ずつ区切った文字列とカンマを追加
input.length / 3.times do |i|
    output += "#{input[i*3,3]},"
end

# 末尾のカンマを除去して出力
puts output.chomp(",")

※不正解です。一旦ギブアップします...

学び

  • 文字列のインデックスを実践的に使う方法を学んだ。
  • chompメソッドは改行だけでなく、,なども除去できる。
1
0
0

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