十进制转二进制
十进制转二进制
代码
javascript
// 十进制转二进制
// 输入:10
// 输出:'1010'
export function decimalToBinary (num) {
let res = ''
while (num > 0) {
res = num % 2 + res
num = ~~(num / 2)
}
return res
}
typescript
// 十进制转二进制
// 输入:10
// 输出:'1010'
export function decimalToBinary (num: number): string {
let res = ''
while (num > 0) {
res = num % 2 + res
num = ~~(num / 2)
}
return res
}
测试代码
ts
import { expect, test } from 'vitest'
import { decimalToBinary } from './typescript.ts'
import { decimalToBinary as decimalToBinaryJs } from './javascript.js'
test(`10 to '1010'`, () => {
expect(decimalToBinary(10)).toBe('1010')
})
test(`10 to '1010'`, () => {
expect(decimalToBinaryJs(10)).toBe('1010')
})