2009-04-17 16 views

Odpowiedz

8

Pseudokod:

bases = [24, 60, 60] 
input = 86462      #One day, 1 minute, 2 seconds 
output = [] 

for base in reverse(bases) 
    output.prepend(input mod base) 
    input = input div base   #div is integer division (round down) 
5

Number -> zestaw:

factors = [52,7,24,60,60,1000] 
value = 662321 
for i in n-1..0 
    res[i] = value mod factors[i] 
    value = value div factors[i] 

I odwrotnie:

Jeśli masz numer jak 32 (52), 5 (7), 7 (24), 45 (60), 15 (60), 500 (1000) i chcesz, aby to było zamienione na dziesiętne:

Weź numer n, pomnóż go współczynnikiem n-1, cd w przypadku n-1..n = 0

values = [32,5,7,45,15,500] 
factors = [52,7,24,60,60,1000] 

res = 0; 
for i in 0..n-1 
    res = res * factors[i] + values[i] 

I masz numer.

+0

Pytanie prosi o przeciwieństwo tego. – Artelius

+0

Tak, poprawiono. Jeszcze się nie obudził. –

+0

Oczywiście. W obu przykładach twoje pętle przechodzą w niewłaściwej kolejności. – Artelius

1

wymyśliłem nieco inny i prawdopodobnie nie tak dobre, jak inne metody te tutaj, ale myślałem, że dzielić i tak:

var theNumber = 313732097; 

//    ms s m h d 
var bases = [1000, 60, 60, 24, 365]; 
var placeValues = []; // initialise an array 
var currPlaceValue = 1; 

for (var i = 0, l = bases.length; i < l; ++i) { 
    placeValues.push(currPlaceValue); 
    currPlaceValue *= bases[i]; 
} 
console.log(placeValues); 
// this isn't relevant for this specific problem, but might 
// be useful in related problems. 
var maxNumber = currPlaceValue - 1; 


var output = new Array(placeValues.length); 

for (var v = placeValues.length - 1; v >= 0; --v) { 
    output[v] = Math.floor(theNumber/placeValues[v]); 
    theNumber %= placeValues[v]; 
} 

console.log(output); 
// [97, 52, 8, 15, 3] --> 3 days, 15 hours, 8 minutes, 52 seconds, 97 milliseconds 
+0

Myślę, że możesz użyć Math.DivRem w swojej drugiej pętli. output [v] = Math.DivRem (theNumber, placeValues ​​[v], out theNumber); – Hafthor

Powiązane problemy