[LeetCode-interview algorithm classic-Java implementation] [013-Roman to Integer (Roman to Integer)], leetcode -- java
[013-Roman to Integer (Roman to Integer )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Theme
Given a roman number, convert it to the corresponding integer.
The entered number is between 1 and.
Solutions
The addition operation is performed based on the ing relationship between the number of Rome and the number of integers. If the first number is greater than the last one, the addition operation is performed.
Code Implementation
Public class Solution {public int romanToInt (String s) {int result = 0; int prev = 0; // record the value of the previous number for (int I = s. length ()-1; I>-1; I --) {switch (s. charAt (I) {case 'I': // 1 if (1 <prev) {result-= 1;} else {result + = 1;} prev = 1; break; case 'V': // 5 if (5 <prev) {result-= 5;} else {result + = 5;} prev = 5; break; case 'X': // 10 if (10 <prev) {result-= 10;} else {result + = 10;} prev = 10; break; case 'l ': // 50 if (50 <prev) {result-= 50;} else {result + = 50;} prev = 50; break; case 'C ': // 100 if (100 <prev) {result-= 100;} else {result + = 100;} prev = 100; break; case 'D ': // 500 if (500 <prev) {result-= 500;} else {result + = 500;} prev = 500; break; case 'M ': // 1000 result + = 1000; prev = 1000; break;} return result ;}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/46963377]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.