0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

0
Last updated at Posted at 2025-08-14

回答その1

console.log(lines[0].toString().replace(/(\d)(?=(\d{3})+"$")/g, '$1,'))

方針

  1. Number型で扱える整数の最大値は9007199254740991のため、文字列に変換する
  2. 正規表現を使用して検索し、該当箇所をreplaceでカンマ変換

正規表現

文字 意味
\d [0-9]
?= 肯定先読み (?=(\d{3})+)の条件が満たされる場合のみ(\d)をマッチさせる
\d{3} 直前の文字 (この場合は \d) が3つある場合一致
+ 直前の文字やグループが1回以上繰り返されることを表す
$ 行の最後
g 複数の箇所に含まれている場合使用
$1 ()の箇所が左から数えて一番目の箇所をさす

回答その2

  1. 右から順に区切るために、reverseを使用し、数字を反転させる
    ( 例 123456789⇨9,8,7,6,5,4,3,2,1)
  2. だがreverseを使用するには配列に変える必要があるため、配列に変更
  3. pliceで要素の4つ目に、カンマを繰り返し挿入。
    例 9,8,7,,6,5,4,,3,2,1,
  4. 数字の順番が反転していたため、元に戻しカンマを入れた状態を結合する
  5. 文字列の最初にカンマが来てしまうケースが発生し場合、
    カンマを抜いた後の文字位置を指定し表示させる。
    発生しなかった場合は、そのまま表示する。
let numberReverse= Array.from(lines[0]).reverse();

const conmma = 3;
const addComma = 4;
const deleteCount = 0;

for (i=0; i<numberReverse.length; i += addComma){
  numberReverse.splice(conmma+i, deleteCount,",")
}

const originalOrderSequenceOfNumbers = numberReverse.reverse("").join("")

count index = 0;

if(originalOrderSequenceOfNumbers.indexOf(",") === index){
  console.log(originalOrderSequenceOfNumbers.slice(1)(",") )
}else{
  console.log(originalOrderSequenceOfNumbers)
}
意味
Array.from 文字列や配列風オブジェクトから新しい配列を生成する
reverse() 配列の要素を元の配列上で逆順に並び替える。元の配列を直接変更する点に注意

indexOf
対象の文字列に指定した文字列が含まれるかどうかを文字列の先頭から検索し、見つかった場合は最初の位置を返す。

文字列.indexOf(検索文字列 [, 開始インデックス])

splice()
既存の要素を取り除いたり、置き換えたり、
新しい要素を追加したりすることで、配列の内容そのものを変更する

配列.splice(start, deleteCount, item1, item2, ..., itemN)

start: 操作を開始する要素のインデックス。
deleteCount: 削除する要素の数。0を指定すると削除は行われない。
item1, item2: 追加する要素。指定しないと削除のみ実行。
今回は削除を行わないため、deleteCountについて0を指定し、要素を追加する

const array = [`あ`, `い`, `う`, `え`, `お`];
const result = array.splice(2, 0, 'a', 'b');

console.log(array); // ['あ', 'い', 'a','b',  'う', 'え','お']
console.log(result) []

slice()
元の文字列を変更せず、文字列の一部分を取り出し、それを新しい文字列として返す

const str = 'あいうえお';

const result = str.slice( 0, 4 );
const test = str.slice(1);

console.log( result ); //[あいうえ]
console.log( test );//[いうえお]

参考記事

その1
https://zenn.dev/unemployed/articles/cab5a35f1a990e
https://ourinttech.com/regex/look-ahead/
https://zenn.dev/ryome/articles/9a28660d27363b
https://userweb.mnet.ne.jp/nakama/

その2
https://zenn.dev/uot/articles/github-zenn-uot-20240420
https://qiita.com/Yasushi-Mo/items/e2d69e8fb9441569
https://pikawaka.com/javascript/splice

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?