• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

从右向左,preVal, curVal

1. curVal >= preVal:  res+=curVal

2. curVal < preVal: res -= curVal

 1 public class Solution {
 2     public static int romanToInt(String s) {
 3         int res = 0;
 4         int preVal = 0;
 5         for (int i = s.length() - 1; i >= 0; i--) {
 6             char c = s.charAt(i);
 7             int curVal = 0;
 8             switch (c) {
 9             case 'I':
10                 curVal = 1;
11                 break;
12             case 'V':
13                 curVal = 5;
14                 break;
15             case 'X':
16                 curVal = 10;
17                 break;
18             case 'L':
19                 curVal = 50;
20                 break;
21             case 'C':
22                 curVal = 100;
23                 break;
24             case 'D':
25                 curVal = 500;
26                 break;
27             case 'M':
28                 curVal = 1000;
29                 break;
30             }
31             if (curVal >= preVal) res += curVal;
32             else res -= curVal;
33             preVal = curVal;
34         }
35         return res;
36     }
37 }

 

 

 

posted @ 2014-05-08 05:23  neverlandly  阅读(305)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3