Skip to content

Commit 35e1fe6

Browse files
authored
algorithm: add IntToBase algo and a test for it (TheAlgorithms#1258)
1 parent 7fb1215 commit 35e1fe6

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

‎Maths/IntToBase.js‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @function intToBase
3+
* @description Convert a number from decimal system to another (till decimal)
4+
* @param{Number} number Number to be converted
5+
* @param{Number} base Base of new number system
6+
* @returns{String} Converted Number
7+
* @see [HornerMethod](https://en.wikipedia.org/wiki/Horner%27s_method)
8+
* @example
9+
* const num1 = 125 // Needs to be converted to the binary number system
10+
* gornerScheme(num, 2); // ===> 1111101
11+
* @example
12+
* const num2 = 125 // Needs to be converted to the octal number system
13+
* gornerScheme(num, 8); // ===> 175
14+
*/
15+
constintToBase=(number,base)=>{
16+
if(typeofnumber!=='number'||typeofbase!=='number'){
17+
thrownewError('Input data must be numbers')
18+
}
19+
// Zero in any number system is zero
20+
if(number===0){
21+
return'0'
22+
}
23+
letabsoluteValue=Math.abs(number)
24+
letconvertedNumber=''
25+
while(absoluteValue>0){
26+
// Every iteration last digit is taken away
27+
// and added to the previous one
28+
constlastDigit=absoluteValue%base
29+
convertedNumber=lastDigit+convertedNumber
30+
absoluteValue=Math.trunc(absoluteValue/base)
31+
}
32+
// Result is whether negative or positive,
33+
// depending on the original value
34+
if(number<0){
35+
convertedNumber='-'+convertedNumber
36+
}
37+
returnconvertedNumber
38+
}
39+
40+
export{intToBase}

‎Maths/test/IntToBase.test.js‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import{intToBase}from'../intToBase'
2+
3+
describe('Int to Base',()=>{
4+
test('Conversion to the binary system',()=>{
5+
expect(intToBase(210,2)).toEqual('11010010')
6+
expect(intToBase(-210,2)).toEqual('-11010010')
7+
})
8+
test('Conversion to the system with base 5',()=>{
9+
expect(intToBase(210,5)).toEqual('1320')
10+
expect(intToBase(-210,5)).toEqual('-1320')
11+
})
12+
test('Conversion to the octal system',()=>{
13+
expect(intToBase(210,8)).toEqual('322')
14+
expect(intToBase(-210,8)).toEqual('-322')
15+
})
16+
test('Output is 0',()=>{
17+
expect(intToBase(0,8)).toEqual('0')
18+
expect(intToBase(0,8)).toEqual('0')
19+
})
20+
test('Throwing an exception',()=>{
21+
expect(()=>intToBase('string',2)).toThrow()
22+
expect(()=>intToBase(10,'base')).toThrow()
23+
expect(()=>intToBase(true,false)).toThrow()
24+
})
25+
})

0 commit comments

Comments
(0)