zoukankan      html  css  js  c++  java
  • 12. Integer to Roman(C++)

    Given an integer, convert it to a roman numeral.

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

    Solution:

    以3999,为例:

    class Solution {
    public:
      string intToRoman(int num) {
        if(num<1||num>3999) return NULL;
        string str;
        while(num){
          if(num/1000!=0){
            for(int i=0;i<num/1000;i++) str+="M";
            num=num%1000;
          }else if(num/100!=0){
            int tmp=num/100;
            if(tmp%5==4){
              if(tmp/5==0){
                str+="C";str+="D";
              }else{  
                str+="C";str+="M";
              }
            }else{
              if(tmp/5!=0){
                str+="D";
              }
              for(int i=0;i<tmp%5;i++) str+="C";
            }
            num=num%100;
          }else if(num/10!=0){
            int tmp=num/10;
            if(tmp%5==4){
              if(tmp/5==0){
                str+="X";str+="L";
              }else{
                str+="X";str+="C";
              }
            }else{
              if(tmp/5!=0){
                str+="L";
              }
              for(int i=0;i<tmp%5;i++) str+="X";
            }
            num=num%10;
          }else{
            if(num%5==4){
              if(num/5==0){
                str+="I";str+="V";
              }else{
                str+="I";str+="X";
              }
            }else{
              if(num/5!=0){
                str+="V";
              }
              for(int i=0;i<num%5;i++) str+="I";
            }
            num=num%1;
          }
        }
        return str;
      }
    };

  • 相关阅读:
    [C#] 逆袭——自制日刷千题的AC自动机攻克HDU OJ
    [安卓] 13、安卓蓝牙定位(一)——如何周期性获得蓝牙节点信号强度?
    [stm32] NRF24L01+USART搞定有线和无线通信
    [安卓] 12、开源一个基于SurfaceView的飞行射击类小游戏
    [安卓] 11、串口蓝牙·将软硬结合进行到底
    [安卓] 10、悬浮窗与获取其他任务信息
    [安卓] 9、线程、VIEW、消息实现从TCP服务器获取数据动态加载显示
    [安卓] 8、VIEW和SURFACEVIEW游戏框架
    [安卓] 7、页面跳转和Intent简单用法
    Git常用命令记录
  • 原文地址:https://www.cnblogs.com/devin-guwz/p/6495565.html
Copyright © 2011-2022 走看看