[Typescript] 124. Binary to Decimal
typescript to Binary Decimal 124
2023-09-14 08:59:11 时间
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>>,
]
相关文章
- 计算时间差工具类(TypeScript/JavaScript)
- TypeScript(6)函数「建议收藏」
- typescript web_typescript文档
- TypeScript 实用工具类型之 Omit 类型
- 智能合约开发——TypeScript 基础(全)
- 快速搭建基于Vue3+Vite2+Arco+Typescript+Pinia后台管理系统模板,文末有福利
- TypeScript 中 type 和 interface 有什么区别?
- typescript 中的时间处理
- typescript 中的 const assertions
- 软件开发入门教程网站之TypeScript Array(数组)
- 软件开发入门教程网之TypeScript 基础语法
- typescript学习笔记
- Typescript 全栈最值得学习的技术栈 TRPC
- ORA-16444: ALTER SYSTEM FLUSH REDO TO STANDBY failed due to a corrupted control file or online log file. ORACLE 报错 故障修复 远程处理
- 利用Oracle TO函数实现数据转换(oracle to_函数)