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

300 - String to Number #22092

Open
acwink opened this issue Jan 14, 2023 · 0 comments
Open

300 - String to Number #22092

acwink opened this issue Jan 14, 2023 · 0 comments
Labels
300 answer Share answers/solutions to a question en in English

Comments

@acwink
Copy link

acwink commented Jan 14, 2023

// your answers
type NumberMap = {
  "0": 0;
  "1": 1;
  "2": 2;
  "3": 3;
  "4": 4;
  "5": 5;
  "6": 6;
  "7": 7;
  "8": 8;
  "9": 9;
};
// 两数相加
type Add<
  A extends number,
  B extends number,
  CountA extends 0[] = [],
  CountB extends 0[] = []
> = CountA["length"] extends A
  ? CountB["length"] extends B
    ? [...CountA, ...CountB]["length"]
    : Add<A, B, CountA, [0, ...CountB]>
  : CountB["length"] extends B
  ? Add<A, B, [0, ...CountA], CountB>
  : Add<A, B, [0, ...CountA], [0, ...CountB]>;

// 两数相乘
// 2 x 5 = 2 + 2 + 2 + 2 
type Mul<
  A extends number,
  B extends number,
  Res extends number = 0,
  Cnt extends 0[] = []
> = Cnt["length"] extends B ? Res : Mul<A, B, Add<A, Res>, [0, ...Cnt]>;

type ToNumber<
  T extends string,
  Res extends number = 0
> = T extends `${infer F}${infer R}`
  ? F extends keyof NumberMap
    ? ToNumber<R, Add<Mul<Res, 10>, NumberMap[F]>>
    : never
  : Res;
@acwink acwink added answer Share answers/solutions to a question en in English labels Jan 14, 2023
@github-actions github-actions bot added the 300 label Jan 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
300 answer Share answers/solutions to a question en in English
Projects
None yet
Development

No branches or pull requests

1 participant