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

2257 - MinusOne #31845

Open
cutimgboy opened this issue Jan 24, 2024 · 0 comments
Open

2257 - MinusOne #31845

cutimgboy opened this issue Jan 24, 2024 · 0 comments
Labels
2257 answer Share answers/solutions to a question zh-CN 简体中文

Comments

@cutimgboy
Copy link

// 你的答案
// 由于有大数,递归会导致深度爆炸, 可以转成字符转进行运算
// -1 对照表
type reduceList = [9, 0, 1, 2, 3, 4, 5, 6, 7, 8]
// 将字符串转为数字
type parseInt<T extends string> = T extends `${infer Digit extends number}` ? Digit : never;
// 翻转字符串
type reverseString<T extends string> = T extends `${infer F}${infer R}` ? `${reverseString<R>}${F}` : '';
// 去掉字符串前面所有的 0
type splitZero<T extends string> = T extends `${infer F}${infer L}` ? F extends '0' ? splitZero<L> : T : '0';
// 递归处理字符串
/**
 * 思路:
 * 1.每次取出最后一位, U 保存 -1 后的数字
 * 2.通过判断 U 是不是等于 '', 来判断当前位需不需要 -1 
 */
type recursiveString<T extends string, U extends string = '', Flag extends string = '0'> = T extends `${infer F}${infer L}`
  ? /** 当字符串可以拆开的时候,需要判断 U*/
    Flag extends '0' // Flag 如果是 '0', 说明当前字符不需要 -1
      ? `${reverseString<T>}${U}`
      : // Flag 如果是 '1', 说明当前字符需要 -1
        // 这里需要判断当前字符是否是 '0'
        F extends '0' 
          ? recursiveString<L, `${reduceList[parseInt<F>]}${U}`, '1'> // 0 下一位需要 -1
          : recursiveString<L, `${reduceList[parseInt<F>]}${U}`, '0'> // 非 0 下一位不需要 -1
  : /** 当字符串拆不开的时候, 说明上面的遍历到头了 */
    U extends '9' ? '-1' : splitZero<U>

type MinusOne<T extends number> = parseInt<recursiveString<reverseString<`${T}`>, '', '1'>>;
@cutimgboy cutimgboy added answer Share answers/solutions to a question zh-CN 简体中文 labels Jan 24, 2024
@github-actions github-actions bot added the 2257 label Jan 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
2257 answer Share answers/solutions to a question zh-CN 简体中文
Projects
None yet
Development

No branches or pull requests

1 participant