Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

6141 - Binary to Decimal #30973

Open
Kakeru-Miyazaki opened this issue Dec 2, 2023 · 0 comments
Open

6141 - Binary to Decimal #30973

Kakeru-Miyazaki opened this issue Dec 2, 2023 · 0 comments
Labels
6141 answer Share answers/solutions to a question ja 日本語

Comments

@Kakeru-Miyazaki
Copy link

// 解答をここに記入
type BinaryToDecimal<S extends string, Counter extends never[] = [never], Ans extends never[] = []> = S extends `${infer Rest}1` ? BinaryToDecimal<Rest, [...Counter, ...Counter], [...Ans, ...Counter]> : S extends `${infer Rest}0` ? BinaryToDecimal<Rest, [...Counter, ...Counter], Ans> : Ans["length"]

非常にシンプルな解答です。

2進数を下(2^0の方)から処理していく再帰で、Counter はその桁に対応する長さを持っています。

Ans は、解答となる数字を配列長で表現するための配列で、S の下一桁が 1 だったら Ans に Counter の要素を追加する(これはその桁の分をインクリメントする行為と同じ)ことで、10進数に変換していきます。

@Kakeru-Miyazaki Kakeru-Miyazaki added answer Share answers/solutions to a question ja 日本語 labels Dec 2, 2023
@github-actions github-actions bot added the 6141 label Dec 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
6141 answer Share answers/solutions to a question ja 日本語
Projects
None yet
Development

No branches or pull requests

1 participant