当前位置:网站首页>Daily question - Roman numeral to integer

Daily question - Roman numeral to integer

2022-06-11 21:57:00 Code loving students

Title Description :

  Rome digital 2 Write to do II , Two parallel 1 .

12 Write to do XII , That is to say X + II .

27 Write to do XXVII, That is to say XX + V + II .

  .

Usually , The small numbers in roman numbers are to the right of the big ones . But there are special cases ,

This special rule only applies to the following six cases :


I  Can be placed in  V (5) and  X (10) Left side , To express 4 and 9.
X  Can be placed in  L (50) and  C (100) Left side , To express 40 and  90. 
C  Can be placed in  D (500) and  M (1000) Left side , To express  400 and  900.

title :

1.  When a small number is to the left of a large number, it means a large number - Small numbers

2.  When a large number is on the right, it means a large number + Small numbers

Then through these two laws , We can find out when Array s[i] <s[I+1] when , We subtract s[i], If greater than, add s[i].

Code implementation :

​
int GetValue(char s){   
    int value;
    switch(s){
        case 'I':value = 1;    break;
        case 'V':value = 5;    break;
        case 'X':value = 10;   break;
        case 'L':value = 50;   break;
        case 'C':value = 100;  break;
        case 'D':value = 500;  break;
        case 'M':value = 1000; break;
    }
    return value;
}
int romanToInt(char* s) {
    int count = 0;
    int n = strlen(s);// Find the length of the incoming character 
    int i,temp;
    for (int i = 0; i < n; ++i) {
        temp = GetValue(s[i]);
        if (i < n - 1 && (temp < GetValue(s[i + 1]))){
            count -= temp;
        } 
        else {
            count += temp;
        }
    }
    return count;
}

​

Be careful : 1.  utilize switch It can save the length of code .

         2. i  Must satisfy less than n-1, Otherwise, when s[i+1] Execution time , Will cross the border to visit .

Finally back to count Value can complete the requirements of the topic .

原网站

版权声明
本文为[Code loving students]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206112135378362.html