码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode ---RomanToInteger

时间:2015-12-21 01:56:41      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

原理:羅馬數字的比較,第i和第i+1的比較,s [i]<s[i+1]    sum = sum-s[i];

s [i]>s[i+1]    sum = sum+s[i];

注意字符串溢出!

 

public static int RomanToInteger(String s) {
        int sum = 0;
        for (int i = 0; i < s.length() - 1; i++) {
            int a = StringToint(s.charAt(i));
            int b = StringToint(s.charAt(i + 1));
            if (a < b)
                sum = sum - a;
            else if (a >= b)
                sum = sum + a;
        }
        return sum;
    }

    public static int StringToint(char a) {
        switch (a) {
        case ‘I‘:
            return 1;
        case ‘v‘:
            return 5;
        case ‘x‘:
            return 10;
        case ‘l‘:
            return 50;
        case ‘c‘:
            return 100;
        case ‘d‘:
            return 500;
        case ‘m‘:
            return 1000;
        }
        return 0;

    }

leetcode ---RomanToInteger

标签:

原文地址:http://www.cnblogs.com/neversayno/p/5062352.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!