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

2020-03-19 进制转化 #13

Open
fanmingfei opened this issue Mar 19, 2020 · 3 comments
Open

2020-03-19 进制转化 #13

fanmingfei opened this issue Mar 19, 2020 · 3 comments

Comments

@fanmingfei
Copy link
Member

实现一个进制转换函数,不要使用toString

function mulBase(num, base){
  // code here
}

mulBase(20, 2) // 10100
mulBase(20, 8) // 24
mulBase(20, 10) // 10
mulBase(20, 16) // 14

mulBase(020, 2) // 10000
mulBase(020, 8) // 20
mulBase(020, 10) // 16
mulBase(020, 16) // 10

mulBase(0x20, 2) // 100000
mulBase(0x20, 8) // 40
mulBase(0x20, 10) // 32
mulBase(0x20, 16) // 20

mulBase(0b10, 2) // 10
mulBase(0b10, 8) // 2
mulBase(0b10, 10) // 2
mulBase(0b10, 16) // 2
@fanmingfei fanmingfei changed the title 2020-03-19 禁止转化 2020-03-19 进制转化 Mar 19, 2020
@xiaosen7
Copy link

xiaosen7 commented Mar 19, 2020

function mulBase(num, base) {
    // code here

    const stack = [];

    let quotient, remainder;//商  余数

    while ((quotient = parseInt(num / base)) !== 0) {
        remainder = num % base;
        stack.unshift(remainder);
        num = quotient;
    }

    stack.unshift(num % base)
    
    console.log(stack.join(''));

}

@LiZhaji
Copy link

LiZhaji commented Mar 19, 2020

function mulBase(num, base){
  const negiativeNum = num < 0
  num = negiativeNum ? -num : num

  const res = []

  do{
    res.unshift(num % base)
    num = Math.trunc(num / base)
  }while (num !== 0)

  return negiativeNum ? -res.join('') : res.join('')

}

@joker1148
Copy link

function mulBase(num, base){
  const result = []
  let number = num
  do{
    result.unshift(number%base)
    number = Math.floor(number/base)
  }while(number!=0)
  return result.join("")
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants