zoukankan      html  css  js  c++  java
  • 13. Roman to Integer

    int romanToInt(char* s)
    {
        int I = 1;
        int V = 5;
        int X = 10;
        int L = 50;
        int C = 100;
        int D = 500;
        int M = 1000;
        int result = 0;
        int index = 0;
        int buff[20];
        int i = 0;
        int temp = 0;
        while(s[index] != '')
        {
            switch (s[index])
            {
            case 'I':buff[index] = I;
                break;
            case 'V':buff[index] = V;
                break;
            case 'X':buff[index] = X;
                break;
            case 'L':buff[index] = L;
                break;
            case 'C':buff[index] = C;
                break;
            case 'D':buff[index] = D;
                break;
            case 'M':buff[index] = M;
                break;
            }
            index++;
        }
    
    //    for(i = 0;i < index;i++)
    //    {
    //        printf("%d",buff[i]);
    //    }
    //    printf("
    index = %d",index);
        i = 0;
        if(index == 1)
        {
            return result = buff[i];
        }
        while(i < index)
        {
            if(buff[i] < buff[i+1])
            {
                temp=buff[i+1] - buff[i];
                i++;
            }
            else if(buff[i] == buff[i+1])
            {
                temp = buff[i] + buff[i+1];
                i++;
            }
            else
            {
                temp = buff[i];
            }
            i++;
            result = result + temp;
            if(i == (index - 1))
            {
                result = result + buff[i];
                break;
            }
        }
        return result;
    }
    

    反思:
    1 因为我是用数组做的,所以在运行过程中一定要注意会不会出现数组的范围不够,或者是出现下标越界。我一开始提交的代码中没有下面这几行语句

        if(index == 1)
        {
            return result = buff[i];
        }
    

    这样就会造成数组下标越界。

  • 相关阅读:
    GeoHash核心原理解析
    线程安全与可重入函数
    malloc和free的实现
    数字金字塔最大路径和——递归
    TCP连接建立与断开
    Gray Code
    C压缩字符串中的空格
    C++链接与装载
    epoll测试实例
    C++之手写strlen函数
  • 原文地址:https://www.cnblogs.com/Manual-Linux/p/10479434.html
Copyright © 2011-2022 走看看