Sum
提出詳細
type Elem = "I" type Formattable = string | number | bigint | boolean | null | undefined type NumToArr<N extends number, Acc extends readonly unknown[]=[]> = Acc["length"] extends N ? Acc : NumToArr<N, [...Acc, Elem]> type TupleToString<T extends readonly unknown[], Acc extends string=""> = T extends [infer T1 extends Formattable, ...infer T2] ? TupleToString<T2, `${Acc}${T1}`> : Acc type Repeat<T, N extends number, Acc extends readonly unknown[]=[]> = Acc["length"] extends N ? Acc : Repeat<T, N, [...Acc, T]> type RepeatString<S extends string, N extends number> = TupleToString<Repeat<S,N>> type Reverse<S extends string> = S extends `${infer S1}${infer S2}` ? `${Reverse<S2>}${S1}` : "" type StringLength<S extends string, Count extends readonly unknown[]=[]> = S extends `${infer S1}${infer S2}` ? StringLength<S2,[...Count,Elem]> : Count["length"] type PadZero<S extends string, N extends number> = NumToArr<N> extends [...NumToArr<StringLength<S>>, ...infer Rest] ? `${RepeatString<"0",Rest["length"]>}${S}` : S type Padded<S extends string, T extends string> = [ `0${PadZero<PadZero<S,StringLength<S>>,StringLength<T>>}`, `0${PadZero<PadZero<T,StringLength<S>>,StringLength<T>>}`] type TrimLeadingZeros<S extends string> = S extends `0${infer S2}` ? S2 : S type CarryOut<Arr extends readonly unknown[]> = Arr extends [...Repeat<Elem,10>, ...infer Rest] ? [1, Rest["length"]] : [0, Arr["length"]] type SumOneDigit<N extends number, M extends number, CarryIn extends 0|1=0> = CarryIn extends 1 ? CarryOut<[...NumToArr<N>, ...NumToArr<M>, Elem]> : CarryOut<[...NumToArr<N>, ...NumToArr<M>]> type SumReverse<NS extends string, MS extends string, CarryIn extends 0|1=0, Acc extends string=""> = NS extends `${infer X extends number}${infer NRest}` ? MS extends `${infer Y extends number}${infer MRest}` ? SumOneDigit<X,Y,CarryIn> extends [infer CarryOut extends 0|1, infer Result extends number] ? SumReverse<NRest, MRest, CarryOut, `${Acc}${Result}`> : never : never : `${Acc}` type Sum<A extends string | number | bigint, B extends string | number | bigint> = Padded<`${A}`,`${B}`> extends [infer A2 extends string, infer B2 extends string] ? TrimLeadingZeros<Reverse<SumReverse<Reverse<A2>, Reverse<B2>>>> : never
提出日時 | 2023-09-19 15:39:33 |
---|---|
問題 | Sum |
ユーザー | sankantsu |
ステータス | Accepted |
import type { Equal, Expect } from '@type-challenges/utils' type cases = [ Expect<Equal<Sum<2, 3>, '5'>>, Expect<Equal<Sum<'13', '21'>, '34'>>, Expect<Equal<Sum<'328', 7>, '335'>>, Expect<Equal<Sum<1_000_000_000_000n, '123'>, '1000000000123'>>, Expect<Equal<Sum<9999, 1>, '10000'>>, Expect<Equal<Sum<4325234, '39532'>, '4364766'>>, Expect<Equal<Sum<728, 0>, '728'>>, Expect<Equal<Sum<'0', 213>, '213'>>, Expect<Equal<Sum<0, '0'>, '0'>>, ]