zoukankan      html  css  js  c++  java
  • leetcode算法题(4)

    问题描述:

    罗马数字包含以下七种字符: I, V, X, LCD 和 M

    我的解答:

    package Simple;

    public class RoamnInt {
    public static void main(String[] args) {
    RoamnInt r = new RoamnInt();
    System.out.println(r.romanToInt("IX"));
    }

    public int romanToInt(String s) {
    //如果前一个数为I,后一个数为V或X要单独考虑
    //如果前一个数为x,后一个数为L或C要单独考虑
    //如果前一个数为C,后一个数为D或M要单独考虑
    //不考虑特殊情况,没出现一个字符就加上对应的数值
    int res = 0;
    for (int i = 0; i < s.length(); i++) {
    char t = s.charAt(i);
    switch (t) {
    case 'I':
    if (i < s.length() - 1 && (s.charAt(i + 1) == 'V' || s.charAt(i + 1) == 'X'))
    res -= 1;
    else res += 1;
    break;
    case 'V':
    res += 5;
    break;
    case 'X':
    if (i < s.length() - 1 && (s.charAt(i + 1) == 'L' || s.charAt(i + 1) == 'C'))
    res -= 10;
    else res += 10;
    break;
    case 'L':
    res += 50;
    break;
    case 'C':
    if (i < s.length() - 1 && (s.charAt(i + 1) == 'D' || s.charAt(i + 1) == 'M'))
    res -= 100;
    else res += 100;
    break;
    case 'D':
    res += 500;
    break;
    case 'M':
    res += 1000;
    break;

    }
    }
    return res;
    }
    }
    自我分析:

  • 相关阅读:
    机器学习个人总结
    yolo buffer is too small for requested array
    anaconda + VSCode + 生产环境配置
    YOLO.h5 下载
    通过爬虫程序深入浅出java 主从工作模型
    KafKa记录
    springboot 整合spark-sql报错
    机器学习项目笔记
    python学习笔记之入门
    django-5-使用数据库
  • 原文地址:https://www.cnblogs.com/iceywu/p/11799580.html
Copyright © 2011-2022 走看看