#convert dec number to roman

1 messages · Page 1 of 1 (latest)

nimble atlas
#

i wrote this code for integer to roman conversion , idk whats wrong in here....help pls.

class Solution {
    public String intToRoman(int num) {
        String ans = "";
        HashMap<String,Integer> map = new HashMap<>();      
        map.put("M",1000);
        map.put("CM",900);
         map.put("D",500);
         map.put("CD",400);
         map.put("C",100);
    map.put("XC",90);
    map.put("L",50);
     map.put("XL",40);
     map.put("X",10);
    map.put("IX",9);
map.put("V",5);
map.put("IV",4);
  map.put("I",1);
        for(String rm: map.keySet()){
            while(num>=map.get(rm)){
                ans = ans + rm;
                num = num-map.get(rm);
            }
        }
        return ans;
    }
}
sonic flaxBOT
#

<@&987246399047479336> please have a look, thanks.

copper pine
#

Is it giving you any errors? Are you getting the wrong answers? What input gives you the wrong answer? You need to give more information if you want quick help. Also please format your code, it's really hard to read the way it is right now.

nimble atlas
weary mist
#

can u give us a simple example?

#

input plus expected output plus current output

#

would also help if u can quickly explain ur thought process with that code logic

#

like, how does it work?

nimble atlas
#

look

weary mist
#

and the expected output?

#

and ur explanation for ur code logic as well please 🙂

nimble atlas
#

expected is

#

"MMMDCCXLIX"

#

my explanation is that

#

im iterating in the map for every key

#

if the nums> first value then it will take that key

#

and i will do num - that value

#

for eg like if we take

#

2334

#

then it will take M for 1000

#

and we will minus 1000

#

1334

#

same step again

#

then we will get 334

#

and so on

#

i think the hashmaps in java are unordered thats why it is giving the wrong output

weary mist
#

otherwise the order is "random"

#

🙂

sonic flaxBOT
#

convert dec number to roman

#

Changed the title to convert dec number to roman.

nimble atlas