zoukankan      html  css  js  c++  java
  • LeetCode: Integer to Roman

    这题因为不知道罗马数是怎么一回事。。就去网上找了答案

     1 class Solution {
     2 public:
     3     string intToRoman(int num) {  
     4       // Start typing your C/C++ solution below  
     5       // DO NOT write int main() function    
     6       char symbol[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
     7       int scale = 1000;
     8       string ret;
     9       for (int i = 6; i >= 0; i -= 2) {
    10           int digit = num / scale;
    11           if (digit != 0) {
    12               if (digit <= 3) ret = ret + string(digit, symbol[i]);
    13               else if (digit == 4) ret = ret + symbol[i] + symbol[i+1];
    14               else if (digit == 5) ret = ret + symbol[i+1];
    15               else if (digit <= 8) ret = ret + symbol[i+1] + string(digit-5, symbol[i]);
    16               else if (digit == 9) ret = ret + symbol[i] + symbol[i+2];
    17           }
    18           num %= scale;
    19           scale /= 10;
    20       }
    21       return ret;
    22     }  
    23 };

     C#

     1 public class Solution {
     2     public string IntToRoman(int num) {
     3         char[] sym = new char[7]{'I', 'V', 'X', 'L', 'C', 'D', 'M'};
     4         int scale = 1000;
     5         string ans = "";
     6         for (int i = 6; i >= 0; i-=2) {
     7             int digit = num / scale;
     8             if (digit != 0) {
     9                 if (digit <= 3) ans  = ans + new string(sym[i], digit);
    10                 else if (digit == 4) ans = ans + sym[i] + sym[i+1];
    11                 else if (digit == 5) ans = ans + sym[i+1];
    12                 else if (digit <= 8) ans = ans + sym[i+1] + new string(sym[i], digit-5);
    13                 else if (digit == 9) ans = ans + sym[i] + sym[i+2];
    14             }
    15             num %= scale;
    16             scale /= 10;
    17         }
    18         return ans;
    19     }
    20 }
    View Code
  • 相关阅读:
    HTML--1标签表格
    HTML--4格式布局
    HTML--3css样式表
    快速制作网页的方法
    表单
    表单练习——邮箱注册
    斐波那契数列
    0125 多线程 继承Thread 练习
    Hash(哈希)
    [COI2007] [luogu P1823] Patrik 音乐会的等待 解题报告 (单调栈)
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3083664.html
Copyright © 2011-2022 走看看