Exercism v3 launches on Sept 1st 2021. Learn more! ๐๐๐

Published at Jul 13 2018
·
0 comments

Instructions

Test suite

Solution

Convert a hexadecimal number, represented as a string (e.g. "10af8c"), to its decimal equivalent using first principles (i.e. no, you may not use built-in or external libraries to accomplish the conversion).

On the web we use hexadecimal to represent colors, e.g. green: 008000, teal: 008080, navy: 000080).

The program should handle invalid hexadecimal strings.

Refer to the Exercism CoffeScript page for getting started with CoffeeScript.

In order to run the test, you can run the test file from the exercise directory:

```
jasmine-node --coffee .
```

All of Computer Science http://www.wolframalpha.com/examples/NumberBases.html

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

```
Hexadecimal = require('./hexadecimal')
describe "Hexadecimal", ->
it "hex 1 is decimal 1", ->
hex = new Hexadecimal("1")
expect(hex.toDecimal()).toEqual(1)
xit "hex c is decimal 12", ->
hex = new Hexadecimal("c")
expect(hex.toDecimal()).toEqual(12)
xit "hex 10 is decimal 16", ->
hex = new Hexadecimal("10")
expect(hex.toDecimal()).toEqual(16)
xit "hex af is decimal 175", ->
hex = new Hexadecimal("af")
expect(hex.toDecimal()).toEqual(175)
xit "hex 100 is decimal 256", ->
hex = new Hexadecimal("100")
expect(hex.toDecimal()).toEqual(256)
xit "hex 19ace is decimal 105166", ->
hex = new Hexadecimal("19ace")
expect(hex.toDecimal()).toEqual(105166)
xit "invalid hex is decimal 0", ->
hex = new Hexadecimal("carrot")
expect(hex.toDecimal()).toEqual(0)
xit "black", ->
hex = new Hexadecimal("000000")
expect(hex.toDecimal()).toEqual(0)
xit "white", ->
hex = new Hexadecimal("ffffff")
expect(hex.toDecimal()).toEqual(16777215)
xit "yellow", ->
hex = new Hexadecimal("ffff00")
expect(hex.toDecimal()).toEqual(16776960)
```

```
module.exports = class Hexadecimal
constructor: (str) ->
@reverse_str = str.split('').reverse().join('')
@CHAR_VALS =
a: 10
b: 11
c: 12
d: 13
e: 14
f: 15
toDecimal: ->
return 0 if (/[^a-f0-9]/).test(@reverse_str)
result = 0
for i in [0..@reverse_str.length - 1]
result += (16 ** i) * @valFor(@reverse_str[i])
result
valFor: (symbol) ->
if @CHAR_VALS[symbol] then @CHAR_VALS[symbol] else symbol
```

A huge amount can be learned from reading other peopleโs code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

- What compromises have been made?
- Are there new concepts here that you could read more about to improve your understanding?

Level up your programming skills with 3,450 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments