LEETCODE-13 Roman to Integer

Source: Internet
Author: User



Problem Description: Given A Roman numeral, convert it to an integer.

Input is guaranteed to being within the range from 1 to3999.

Problem Analysis:{' M ', ' D ', ' C ', ' L ', ' X ', ' V ', ' I '}; corresponding to {, 5, 1} respectively;

When there is a similar CM situation, that is, the smaller in front of the larger, then the larger should be subtracted from the smaller, that is, 1000-100=900;

Otherwise, it is added directly;

This is used to store the HashMap , the time complexity ofget () is O (1), and space is used to change the time

Only need to pay attention to the condition judgment and carry case can

Code:

public class Solution {public int romantoint (String s) {if (s = = NULL | | s.length () = = 0) return 0;char[] Numberchars = {' M ' , ' D ', ' C ', ' L ', ' X ', ' V ', ' I '};int[] values = {1000, 500, 100, 50, 10, 5, 1}; Hashmap<character, integer> map = new hashmap<> (); for (int i = 0; i < numberchars.length; i++) {Map.put (Numbe Rchars[i], values[i]);} int result = 0;char[] Datas = S.tochararray (), int i = 1;int last = Map.get (datas[0]), int now = 0;while (i <= datas.lengt h) {if (I <= datas.length-1) {now = Map.get (Datas[i]), if (now > last) {result + = (now-last); ++i;if (I < Datas.leng th) Last = Map.get (Datas[i]);} Else{result + = Last;last = Now;}} Else{result + = Last;last = Now;} ++i;} return result;}}

LEETCODE-13 Roman to Integer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.