Skip to content

Latest commit

 

History

History
43 lines (37 loc) · 862 Bytes

412.fizz-buzz.md

File metadata and controls

43 lines (37 loc) · 862 Bytes

412.fizz-buzz

/*
 * @lc app=leetcode.cn id=412 lang=typescript
 *
 * [412] Fizz Buzz
 */

// @lc code=start
function fizzBuzz(n: number): string[] {}
// @lc code=end

解法 1: 按照规则一步步写即可

function fizzBuzz(n: number): string[] {
  const answer: string[] = []
  for (let i = 1; i <= n; i++) {
    let s = ''
    if (!(i % 3)) s += 'Fizz'
    if (!(i % 5)) s += 'Buzz'
    answer.push(s ? s : `${i}`)
  }
  return answer
}

Case

test.each([
  { input: { n: 3 }, output: ['1', '2', 'Fizz'] },
  { input: { n: 5 }, output: ['1', '2', 'Fizz', '4', 'Buzz'] },
  {
    input: { n: 15 },
    output: ['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz'],
  },
])('input: n = $input.n', ({ input: { n }, output }) => {
  expect(fizzBuzz(n)).toEqual(output)
})