[Typescript] 124. Binary to Decimal
Implement BinaryToDecimal<S>
which takes an exact string type S
consisting 0 and 1 and returns an exact number type corresponding with S
when S
is regarded as a binary. You can assume that the length of S
is equal to or less than 8 and S
is not empty.
type Res1 = BinaryToDecimal<'10'>; // expected to be 2
type Res2 = BinaryToDecimal<'0011'>; // expected to be 3
/* _____________ Your Code Here _____________ */
type NumberToArray<T extends number, R extends 1[] = []> = R['length'] extends T ? R : NumberToArray<T, [...R, 1]>;
type GetTwice<T extends unknown[]> = [...T, ...T];
type BinaryToDecimal<S extends string, Result extends unknown[] = []> = S extends `${infer First extends number}${infer RT}`
? BinaryToDecimal<RT, [...GetTwice<Result>, ...NumberToArray<First>]>
: Result['length'];
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<BinaryToDecimal<'10'>, 2>>,
Expect<Equal<BinaryToDecimal<'0011'>, 3>>,
Expect<Equal<BinaryToDecimal<'00000000'>, 0>>,
Expect<Equal<BinaryToDecimal<'11111111'>, 255>>,
Expect<Equal<BinaryToDecimal<'10101010'>, 170>>,
]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2019-12-02 [CSS3] Use media query to split css files and Dark mode (prefers-color-scheme: dark)
2019-12-02 [PWA] Storage information for PWA application
2019-12-02 [HTML5] Native lazy-loading for the web
2019-12-02 [Dynamic Programming] 198. House Robber
2016-12-02 [D3] Create Labels from Non-numeric Data with Ordinal Scales in D3 v4
2016-12-02 [D3] Create Labels from Numeric Data with Quantize Scales in D3 v4
2016-12-02 [D3] Convert Dates to Numeric Values with Time Scales in D3 v4