Skip to content

Latest commit

 

History

History
44 lines (38 loc) · 842 Bytes

1945.字符串转化后的各位数字之和.md

File metadata and controls

44 lines (38 loc) · 842 Bytes

1945.字符串转化后的各位数字之和

/*
 * @lc app=leetcode.cn id=1945 lang=typescript
 *
 * [1945] 字符串转化后的各位数字之和
 */

// @lc code=start
function getLucky(s: string, k: number): number {}
// @lc code=end

解法 1: 模拟

function getLucky(s: string, k: number): number {
  let a = s
    .split('')
    .map(ch => ch.charCodeAt(0) - 96)
    .join('')
  while (k--) {
    a = a
      .split('')
      .map(Number)
      .reduce((a, b) => a + b, 0)
      .toString()
  }
  return Number(a)
}

Case

test.each([
  { input: { s: 'iiii', k: 1 }, output: 36 },
  { input: { s: 'leetcode', k: 2 }, output: 6 },
  { input: { s: 'zbax', k: 2 }, output: 8 },
])('input: s = $input.s, k = $input.k', ({ input: { s, k }, output }) => {
  expect(getLucky(s, k)).toEqual(output)
})