Robert Eisele
Engineer, Systems Architect and DBA

Codefights: Computer Units to Byte

Original Problem

Given the capacity of a hard drive and its measure unit, return its capacity in bytes.

Here are all possible measure units and their sizes:

Kilobyte (KB)1,024 bytes
Megabytes (MB)1,048,576 bytes
Gigabyte (G)1,073,741,824 bytes
Terabyte (TB)1,099,511,627,776 bytes
Petabyte (P)1,125,899,906,842,624 bytes

Example

For capacity = 12 and unit = "KB", the output should be

`ComputerUnitsToByte(capacity, unit) = "12288".

12 * 1024 = 12288, which is the answer.

Input/Output

  • [time limit] 4000ms (php)
  • [input] integer capacity

    Disk capacity.

    Constraints:

    1 ≤ capacity ≤ 100.

  • [input] string unit

    Unit symbol, one of the following strings: 'KB', 'MB', 'G', 'TB'or 'P'.

  • [output] string

    The answer as a string. It is guaranteed to be smaller than 251.

Solution

The solution is quite obvious that the capacity must be multiplied by a power with base 1024, based on the unit. So KB is \(1024^1\), MB is \(1024^2\) and so on. In order to have a solution which is as short as possible, we'll use some JavaScript trickery. As we can assume, that only the given units are passed as argument, we focus on the first character and search this character in a string:

ComputerUnitsToByte = (c, u) =>
   c * Math.pow(1024, 1 + "KMGTP".indexOf(u[0])) + ""

Since JavaScript doesn't have int64 support, a lot of other tricks don't work and as such I had the shortest solution with this snippet.

Go to overview