Largest Roman Numeral possible by rearranging characters of a given string | Java program for the above approach ; Function to find decimal value of a roman character ; Function to convert string representing roman number to equivalent decimal value ; Stores the decimal value of the string S ; Stores the size of the S ; Update res ; Traverse the string ; Return res ; Function to convert decimal to equivalent roman numeral ; Stores the string ; Stores all the digit values of a roman digit ; Iterate while number is greater than 0 ; Return res ; Function to find largest roman value possible by rearranging the characters of the string ; Stores all roman characters ; Traverse the string ; If X is not found ; Stores the decimal value of the roman number ; Find the roman value equivalent to the decimal value of N ; Return result ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int charVal ( char c ) { if ( c == ' I ' ) return 1 ; if ( c == ' V ' ) return 5 ; if ( c == ' X ' ) return 10 ; if ( c == ' L ' ) return 50 ; if ( c == ' C ' ) return 100 ; if ( c == ' D ' ) return 500 ; if ( c == ' M ' ) return 1000 ; return - 1 ; } static int romanToDec ( String S ) { int res = 0 ; int n = S . length ( ) ; res = charVal ( S . charAt ( n - 1 ) ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( charVal ( S . charAt ( i ) ) < charVal ( S . charAt ( i + 1 ) ) ) res -= charVal ( S . charAt ( i ) ) ; else res += charVal ( S . charAt ( i ) ) ; } return res ; } static String DecToRoman ( int number ) { String res = " " ; int num [ ] = { 1 , 4 , 5 , 9 , 10 , 40 , 50 , 90 , 100 , 400 , 500 , 900 , 1000 } ; String sym [ ] = { " I " , " IV " , " V " , " IX " , " X " , " XL " , " L " , " XC " , " C " , " CD " , " D " , " CM " , " M " } ; int i = 12 ; while ( number > 0 ) { int div = number / num [ i ] ; number = number % num [ i ] ; while ( div -- > 0 ) { res += sym [ i ] ; } i -- ; } return res ; } static String findLargest ( String S ) { char arr [ ] = { ' I ' , ' V ' , ' X ' , ' L ' , ' C ' , ' D ' , ' M ' } ; Set < Character > st = new HashSet < > ( ) ; for ( char x : arr ) st . add ( x ) ; Character s [ ] = new Character [ S . length ( ) ] ; for ( int i = 0 ; i < S . length ( ) ; i ++ ) s [ i ] = S . charAt ( i ) ; for ( char x : s ) { if ( ! st . contains ( x ) ) return " Invalid " ; } Arrays . sort ( s , new Comparator < Character > ( ) { @ Override public int compare ( Character x , Character y ) { return charVal ( y ) - charVal ( x ) ; } } ) ; String ss = " " ; for ( char ch : s ) ss += ch ; int N = romanToDec ( ss ) ; String R = DecToRoman ( N ) ; if ( ! ss . equals ( R ) ) return " Invalid " ; return ss ; } public static void main ( String [ ] args ) { String S = " MCMIV " ; int N = S . length ( ) ; System . out . println ( findLargest ( S ) ) ; } }