十进制转其他进制
十进制转其他进制
代码
javascript
export function getMapNumberToString (base) {
const res = {}
if (base < 10) return res
const strList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
let curIndex = 10
while (curIndex < base) {
res[curIndex] = strList[curIndex - 10]
curIndex++
}
return res
}
typescript
export function getMapNumberToString (base: number) {
const res: { [key: string]: string } = {}
if (base < 10) return res
const strList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
let curIndex = 10
while (curIndex < base) {
res[curIndex] = strList[curIndex - 10]
curIndex++
}
return res
}
javascript
// 十进制转其他进制
// 输入:decimalToOtherBase(10, 2)
// 输出:'1010'
import { getMapNumberToString } from "../../utilsJs"
export function decimalToOtherBase (num, base) {
if (base === 10 || base > 36 || base < 2) return String(num)
const numToStr = getMapNumberToString(base)
let res = ''
while (num > 0) {
const remainder = num % base
const curStr = remainder > 9 ? numToStr[remainder] : remainder
res = curStr + res
num = ~~(num / base)
}
return res
}
typescript
// 十进制转其他进制
// 输入:decimalToOtherBase(10, 2)
// 输出:'1010'
import { getMapNumberToString } from "../../utils"
export function decimalToOtherBase (num: number, base: number): string {
if (base === 10 || base > 36 || base < 2) return String(num)
const numToStr = getMapNumberToString(base)
let res = ''
while (num > 0) {
const remainder = num % base
const curStr = remainder > 9 ? numToStr[remainder] : remainder
res = curStr + res
num = ~~(num / base)
}
return res
}
测试代码
ts
import { expect, test } from 'vitest'
import { decimalToOtherBase } from './typescript.ts'
import { decimalToOtherBase as decimalToOtherBaseJs } from './javascript.js'
test(`decimalToOtherBase(10, 2)`, () => {
expect(decimalToOtherBase(10, 2)).toBe('1010')
})
test(`decimalToOtherBaseJs(10, 2)`, () => {
expect(decimalToOtherBaseJs(10, 2)).toBe('1010')
})
test(`decimalToOtherBase(30, 8)`, () => {
expect(decimalToOtherBase(30, 8)).toBe('36')
})
test(`decimalToOtherBaseJs(30, 8)`, () => {
expect(decimalToOtherBaseJs(30, 8)).toBe('36')
})
test(`decimalToOtherBase(30, 16)`, () => {
expect(decimalToOtherBase(30, 16)).toBe('1e')
})
test(`decimalToOtherBaseJs(30, 16)`, () => {
expect(decimalToOtherBaseJs(30, 16)).toBe('1e')
})
test(`decimalToOtherBase(34, 12)`, () => {
expect(decimalToOtherBase(34, 12)).toBe('2a')
})
test(`decimalToOtherBaseJs(34, 12)`, () => {
expect(decimalToOtherBaseJs(34, 12)).toBe('2a')
})
test(`decimalToOtherBase(100, 36)`, () => {
expect(decimalToOtherBase(100, 36)).toBe('2s')
})
test(`decimalToOtherBaseJs(100, 36)`, () => {
expect(decimalToOtherBaseJs(100, 36)).toBe('2s')
})
test(`decimalToOtherBase(10, 38)`, () => {
expect(decimalToOtherBase(10, 38)).toBe('10')
})
test(`decimalToOtherBaseJs(10, 38)`, () => {
expect(decimalToOtherBaseJs(10, 38)).toBe('10')
})