LeetCode 13. Roman to Integer C++

Leetcode | C++ 13 Roman to integer 题目描述 Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999 解题思路 我们注意到罗马数字的字母是有规律的,可以分成几组,I(1), V(5) 是一组, X(10), L(50)是一组, C(100), D(500)是一组, M(1000), d(应该是D加一个上划线,表示5000) 是一组 ……。后一组的两个数是前一组的10倍。 对于大于10 阅读详情

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III"
Output: 3

Example 2:

Input: "IV"
Output: 4

Example 3:

Input: "IX"
Output: 9

Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

AC代码 ( c++ )

class Solution {
public:
	int charToInt(char ch){
		switch(ch)
		{
			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;
			default : return 0;
		}
	}
    int romanToInt(string s) {
        int index = 0;
        int res = 0;
        while(s[index]!='\0'){
        	if( charToInt(s[index]) < charToInt(s[index+1]) ){
        		res += charToInt( s[index+1] ) - charToInt (s[index]) ; //比如 IV IX.
                index++;
			}else{
				res += charToInt(s[index]);
			}
            index++;
		}
		return res;
    }
};

C++ 二刷

class Solution {
public:
	int charToInt(char ch){
		switch(ch)
		{
			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;
			default : return 0;
		}
	}
    int romanToInt(string s) {
        int index = 0;
        int res = 0;
        for(int i = 0; i < s.size(); i++){
            if(charToInt(s[i]) >= charToInt(s[i+1]) ) res += charToInt(s[i]);
            else res -= charToInt(s[i]);
        }
		return res;
    }
};

首先建立一个函数来映射符号和值,然后对字符串从左到右来,如果当前字符代表的值不小于其右边,就加上该值;否则就减去该值。以此类推到最左边的数,最终得到的结果即是答案

手把手教你用Python 3.11和Node.js 18在Windows 11上搭建Dify开发环境 本文提供了一份详尽的Windows 11本地Dify开发环境搭建指南。文章手把手教你完成从Python 3.11、Node.js 18的安装配置,到PostgreSQL、Redis数据库服务的部署,再到前后端服务的启动与联调的全过程,并包含常见问题排查与效能优化建议,旨在帮助开发者构建一个稳定、可调试的Dify本地开发环境。 阅读详情

相关推荐

TouchGFX移植踩坑实录:SPI Flash下载算法制作与分散加载(.sct)配置详解

本文详细解析了TouchGFX在STM32平台上的深度移植实战,重点探讨了SPI Flash下载算法制作与分散加载(.sct)配置的技术难点。通过具体案例和代码示例,指导开发者解决外部存储管理、资源分配及运行时效率等核心问题,助力嵌入式GUI开发效率提升。

weixin_30735745的博客 423

leetcode 13 Roman to Integer C++

这道题主要是要知道罗马转数字的规则,前边的比后边的小就要减。 int romanToInt(string s) { int a[26] = {0}; a['I'-'A'] = 1; a['V'-'A'] = 5; a['X'-'A'] = 10; a['L'-'A'] = 50; a['C'-'A'] = 100; a['D

wcxdell的专栏 797

C#操作SQLite数据库帮助类——SQLiteHelper

using System; using System.Collections.Generic; using System.Data.SQLite; using System.Data; namespace Com.ZCWL.Rock.Helper { public class SQLiteHelper { private static string connectionString =

跟健哥出去走走 2万+

【leetcode c++】13 Roman to Integer

题目 Given a roman numeral, convert it to aninteger. Input is guaranteed to be within the rangefrom 1 to 3999.   输入一个1-3999的罗马数字(字符串),转化成整型。   首先,我们要大致知道罗马数字。 参考百度百科,主要本题要用的资料: 基本字符 I=1 V=5 X

lif的博客 795

Xiaojie雷达之路---使用CCS创建一个毫米波雷达的工程(AWR1843)

前些天,在工具箱中下载了一个基于毫米波雷达(AWR1843)自动停车的案例,并成果导入CCS中,可以完美运行,但是如何新建一个新的工程呢?这篇文章就会对其进行讲述。

XiaoJie的博客 4561

高光谱目标检测底层逻辑:假设检验、SNR与光谱角度理论解析

高光谱目标检测在遥感应用中常被视作光谱匹配问题,但其本质是统计判决。从假设检验的框架出发,每个像元都需要在目标与背景之间做出二元判断,Neyman-Pearson准则为不依赖先验概率的最优判决提供了依据。而检测性能的上限由信噪比决定,信噪比直接影响目标与背景分布的重叠程度。在高光谱场景中,光谱角度作为方向型特征,对光照和尺度变化具有天然鲁棒性,成为区分光谱形状差异的有效度量。结合工程实践,从建模、信噪比估算到特征选择,再到检测器设计,这一套底层逻辑能帮助我们理解为何不同算法在不同数据上效果差异巨大。本文围绕

weixin_29034963的博客 299

Leetcode 13. Roman to Integer (cpp)

题目 解法: 写个while循环,单独处理特殊情况即可 class Solution { public: int romanToInt(string s) { unordered_map<char,int> mapping{ {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100},

qq_37821701的博客 167

【Qt】使用QMediaPlayer播放视频

window平台可以安装K-Lite,linux平台一般各发行版都会默认安装GSteam。播放RTSP视频时,可以使用VLC播放器搭建一个视频推流服务器,用于拉流的客户端的调试。3、如果没有添加Qt环境变量,请把关联的Qt5MultimediaWidgets.dll和Qt5Multimedia.dll放到进程路径下否则也会报ServiceMissingError错误。2、需要安装解码器,否则报 ServiceMissingError 无法找到服务的错误。1、需要在.pro工程文件中引用对应模块。

奔涌的后浪的专栏 2223

Leetcode 13. Roman to Integer (Easy) (cpp)

Leetcode 13. Roman to Integer (Easy) (cpp)

还是需要多学习!闷声大发财,这是坠吼的! 368

DEA-Malmquist指数模型实战:从理论到应用的全流程解析

本文全面解析了DEA-Malmquist指数模型从理论到应用的全流程。文章详细阐述了该模型如何动态衡量效率随时间的变化,并将其分解为技术效率变化与技术进步,从而精准定位效率变动的根源。通过实战步骤演示了数据准备、软件操作(如DEAP 2.1)及结果解读,并结合水资源环境效率等案例,展示了其在包含非期望产出时的应用价值,为研究者进行动态效率分析提供了清晰指南。

b0c1d2的博客 229

Spring AI 实战:第七章、Spring AI Advisor机制之记忆大师

从金鱼到最强大脑通过 Spring AI 的记忆功能,我们成功让 AI:记住了用户身份实现了多用户隔离做到了持久化存储最终效果用户:“和上次一样” → AI 秒懂用户:“你知道我的名字吗?” → AI:“当然,张三!AI的进化路线🐟金鱼脑 →🧠最强大脑 →🏛️记忆宫殿管理员。

liaokailin的专栏 1524

LeetCode C++ 13. Roman to Integer【String/Hash Table】简单

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, 2 is writt

memcpy0的博客 397

uniapp - [微信小程序 | 安卓苹果app] 详细实现接入天地图完整流程,提供显示地图、IP 属地定位 / 用户定位的城市名称、用户定位的经纬度超多功能(复制运行示例代码,详细注释及常见问题)

uni-app,微信小程序,安卓app,苹果app,App端,支付宝小程序,nvue,天地图,国家天地图api,接入使用天地图,uniApp小程序端接入天地图,uniapp安卓苹果app端接入天地图,微信小程序平台如何引入天地图,天地图Api使用教程,如何在uniapp里集成天地图,使用天地图获取当前定位,天地图api教程,天地图官方文档,天地图详细使用教程,Uniapp项目如何使用天地图,项目引入天地图配置及使用教程,使用天地图获取用户定位,天地图获取用户当前位置信息(经纬度),如何通过天地图拿到用户定位

🏆 前端领域优质创作者 1万+

LeetCode - 13. Roman to Integer - 思考if-else与switch的比较 - ( C++ ) - 解题报告

1.题目: 原题:Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Subscribeto see which companies asked this questio 解析:给出一个罗马数字,要求把其转换为一个整数。输入范...

weixin_30721899的博客 86

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LeetCode13-Roman to Integer(C++)

Description Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I              &...

PengQ1的博客 359

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

LeetCode13. Roman to Integer(C++/Python)

Roman numerals are represented by seven different symbols:I,V,X,L,C,DandM. Symbol Value I 1 V 5 X 10 L 50 C 100 D ...

qq_41562704的博客 402

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

LeetCode(13) RomanToInteger

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. 本题是把一个罗马数字转化为阿拉伯数字,和前道题目正好相反。我按照千位、百位、十位、个位的顺序依次处理罗马数字。在前一到题目的解答中,可以找到一个办法去简化代码,本题好像不怎么方

BUILD 3363

leetcode13:Roman to Integer罗马数字转整形

题目: Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 ...

别说话写代码的博客 343

【LeetCode】13. Roman to Integer

Roman numerals are represented by seven different symbols:I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D ...

韩旭051的博客 636

leetcode13. Roman to Integer

心想用python里的dist会很简单,于是找了c++里面有没有类似的东西,找到了map,于是借此学习了一下c++里面的map的操作。find()返回迭代器。 map&lt;string,int&gt; cmap; cmap["op1"] = 1; cmap["op2"] = 2; string str = "samy"; cmap.inser...

zilu0907的博客 205

13. Roman to Integer (第一周)

Roman to Integer - LeetCode Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999. Input: "DCXXI" Output: 621Solution

qq1997722的博客 412

[Leetcode] 13 - Roman to Integer

原题链接:https://oj.leetcode.com/problems/roman-to-integer/ 比较简单的题,代码应该还可以稍微优化,更generic一些。 class Solution { public: int romanToInt(string s) { if (s.size() == 0) return 0;

AlgorithmEngine 711

[LeetCode 13] Roman to Integer

Roman numerals are represented by seven different symbols:I,V,X,L,C,DandM. Symbol Value I 1 V 5 X 10 L 50 C 100 D ...

ExcitedZhang的博客 142

13 Roman to Integer

13 Roman to Integer链接:https://leetcode.com/problems/roman-to-integer/ 问题描述: Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.Hide Tags Math St

599

13. Roman to Integer LeetCode题解

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Subscribe to see which companies asked this question. 题意: 给定一个罗马数字,将其转换为整数。 输入数

水之如此的专栏 426

13 Roman to Integer

罗马数字转换数字,行吧,你开心就好。 两个是不是可以形成一个永动机,你转化为我,我再转化为你。。。然后堆栈溢出,电脑爆炸,世界毁灭。 按照上题,列出来所有的 M、 CM、D、CD、C、XC、L、XL、X、IX、V、IV、I int romanToInt(string s) { map<string, int> romanHash; rom...

cxhttt的博客 321
上一篇: LeetCode 12. Integer to Roman C++
下一篇: LeetCode 14. Longest Common Prefix C++
ganlanA
博客等级 码龄7年 898粉丝 398原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值