December 23, 2024
Roman Numerals Decoder

Belajar Bahasa C – Roman Numerals Decoder

Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don’t need to validate the form of the Roman numeral.

Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered “MCMXC” (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered “MMVIII” (2000 = MM, 8 = VIII). The Roman numeral for 1666, “MDCLXVI”, uses each letter in descending order.

Example:

solution('XXI'); // should return 21

The problem link is here.

Solution:

#include <string.h>

int roman_val(char roman)
{
  int val = 0;

  switch (roman)
  {
  case 'I':
    return val = 1;
    break;
  case 'V':
    return val = 5;
    break;
  case 'X':
    return val = 10;
    break;
  case 'L':
    return val = 50;
    break;
  case 'C':
    return val = 100;
    break;
  case 'D':
    return val = 500;
    break;
  case 'M':
    return val = 1000;
    break;
  }
  return val;
}

unsigned decode_roman(const char *roman_number)
{
  unsigned long len = strlen(roman_number);
  unsigned i, n, m, value = 0;

  for (i = 0; i < len; i++)
  {
    n = roman_val(roman_number[i]);
    m = roman_val(roman_number[i + 1]);

    if (n >= m)
      value += n;
    else if (n < m)
      value += (m - n), i++;
  }
  return value;
}

Rajo Intan

Blogger, pemiliki Onestring Lab, menulis artikel terkait teknologi informasi dan pendidikan. Web Developer, berpengalaman lebih dari 20 tahun mengembangkan berbagai aplikasi dan sistem informasi. Kerjasama kontak di onestringlab@gmail.com atau https://forms.gle/xAGKkpi6B3BzJyzk7

View all posts by Rajo Intan →

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
100% Free SEO Tools - Tool Kits PRO