Skip to content

Instantly share code, notes, and snippets.

@1n3ffbl3
Created April 11, 2018 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 1n3ffbl3/ab48fb293d5943d44ba90780e9d50cf8 to your computer and use it in GitHub Desktop.
Save 1n3ffbl3/ab48fb293d5943d44ba90780e9d50cf8 to your computer and use it in GitHub Desktop.
Challenge from 10_04_2018
function challenge1 (a, b, c){
let base1 = Number.parseInt(a, b);
let base2 = Number.parseInt(base1, c);
return base2.toString();
}
console.log(challenge1 (10, 2, 10))
function base2base (n, base1, base2){
var ourNumber = 0;
for (var number_position= n.length - 1, i = 0; number_position >= 0; -- number_position, i++){
ourNumber += n[number_position]*Math.power(base1, i)
}
return ourNumber.toString(base2);
}
console.log(base2base (10, 2, 10))
*/
Podejscie proste wbudowane:
znajdz w dokumentacji opis funkcji parseInt i wykorzystaj odpowiednio
Podejscie iteracyjne
function base2base(n, base1, base2) {
var liczba = 0
for number_position = n.length - 1, iterator = 0 ; number_position >= 0 ; --number_position, ++iterator {
liczba += n[number_position] * (base1 ** iterator)
}
return liczba.toString(base2)
}
n = 10011 = 1 * 2**4 + 0 * 2 ** 3 + 0 * 2 ** 2 + 1 * 2 ** 1 + 1 * 2 ** 0 = 19
b1 = 2
b2 = 10
1 loop:
number_position = 5 - 1 = 4
iterator = 0
n[number_position] = 1
base1 ** iterator = 2 ** 0 = 1
liczba = 0 + 1
2 loop:
number_position = 3
iterator = 1
n[number_position] = 1
base1 ** iterator = 2 ** 1 = 2
liczba = 1 + 2 = 3
3 loop:
number_position = 2
iterator = 2
n[number_position] = 0
base1 ** iterator = 2 ** 2 = 4
liczba = 3 + 0
4 loop:
number_position = 1
iterator = 3
n[number_position] = 0
base1 ** iterator = 2 ** 3 = 8
liczba = 3 + 0
5 loop:
number_position = 0
iterator = 4
n[number_position] = 1
base1 ** iterator = 2 ** 4 = 16
liczba = 3 + 16 = 19
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment