write my solution for leetcode


  • 0
    L

    we konw Roman is made of 'I','V','X','L','C','D','M',and them are 1,5,10,50,100,500,1000.

    so if give us a integer,we can do something as belowing
    **StringBuilder sb = new StringBuilder();
    int gw = n % 10;
    n -= gw;
    int sw = n % 100;
    n -= sw;
    int bw = n % 1000;
    n -= bw;

    int count = n / 1000;
    while(count != 0){
    sb.append('M');
    count--;
    }**
    now we have bean got the roman's 'M';

    the rest,we can group it.for example.
    bw>= 100 && bw < 400 in this case,we can get a String is made of 'C'
    bw == 400 in this case,we can get a String "CD"
    bw >= 500 && bw < 900 in this case,we can get a String starting with 'D',and the rest is made of many 'C'
    bw == 900 in this case,we can get a String "CM"

    gw,sw are aslo possible to do like this,so we can write a method to process this case

    public void getRoman(int w,int q,StringBuilder sb,char a,char b,char c){
    int count;
    if(w == 0)
    return;
    if(w >= 1 * q && w < 4 * q){
    count = w / q;
    while(count != 0){
    sb.append(a);
    count--;
    }
    }else if(w == 4 * q){
    sb.append(a).append(b);
    }else if(w >= 5 * q && w < 9 * q){
    sb.append(b);
    count = (w - 5 * q) / q;
    while(count != 0){
    sb.append(a);
    count--;
    }
    }else{
    sb.append(a).append(c);
    }
    }
    And call it like belowing

    getRoman(bw,100,sb,'C','D','M');
    getRoman(sw,10,sb,'X','L','C');
    getRoman(gw,1,sb,'I','V','X');


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.