In this segment of code, from everything I'm seeing, it should be entering the for loop and then the if statement as long as you enter 1's and 0's, which is what I'm doing. It's not entering it, as I've seen from my print statements.
I don't see a reason why.
If it did enter the if statement, I also am unsure what to do because my suspicion is that it will only set true if the last bit is not a 1 or 0: my intention being for zeroesAndOnes to be false if anything except 1's and 0's are entered. However, as it stands, it's false all the time.
System.out.println("Please enter a 32 bit number consisting of "
+ "1's and 0's.");
String number = kb.nextLine();
int count = 0;
boolean zeroesAndOnes = false;
for(int i = 0; i < number.length(); i++){
if(number.charAt(i) == '0' || number.charAt(i) == '1'){
zeroesAndOnes = true;
System.out.println("If boolean " + zeroesAndOnes);
}
else{
zeroesAndOnes = false;
count++;
}
}
System.out.println("If boolean end " + zeroesAndOnes);
if(number.length() == 32 && count > 1){
if(number.charAt(0) + number.charAt(1) % 2 == 1){
symmDiff = 1;
}
else{
symmDiff = 0;
}
for(int i = 2; i < number.length(); i++){
if((symmDiff + number.charAt(i)) % 2 == 1){
symmDiff = 1;
}
else{
symmDiff = 0;
}
}
System.out.println("The parity bit for this number is " + symmDiff);
}
else{
System.out.println("These numbers do not match the specification.");
}
When checking for char equality, be sure the comparison is what you need. For instance
if(number.charAt(i) == 0)
checks for decimal value equality. To check for an actual '0' char, compare the char value
if ( number.charAt(i) == '0' )
for comparing a char you should use
if(number.chartAt(i) == '0')
another issue is number.charAt(0) will give you char not int. so when you are doing
number.charAt(0)+number.charAt(1) //you are concatenating character at index 0 and index 1
// do this
int first = Integer.parseInt(number.substring(0,1));
int second = Integer.parseInt(number.substring(1,2));
if( (first+second)%2 == 1){
// your statement
}
Related
Hey' all so im figuring out how to multiply bigintegers without importing them and I have it almost all. The only thing that isnt working is when multiplying with -digit the output is still +. any help appreciated. ie. -20*4=80
Scanner scan = new Scanner(System.in);
System.out.println("Type the first number:");
String x = scan.nextLine();
System.out.println("Type the second number:");
String y = scan.nextLine();
if (x.charAt(0) == '-' && y.charAt(0) != '-') {
x = x.substring(1);
}
else if (x.charAt(0) != '-' && y.charAt(0) == '-') {
y = y.substring(1);
}
else if (x.charAt(0) == '-' && y.charAt(0) == '-') {
x = x.substring(1);
y = y.substring(1);
}
String s1 = new StringBuffer(x).reverse().toString();
String s2 = new StringBuffer(y).reverse().toString();
int[] m = new int[s1.length() + s2.length()];
for (int i=0; i<s1.length(); i++) {
for (int j=0; j<s2.length(); j++) {
m[i+j] = m[i+j] + (s1.charAt(i) - '0') * (s2.charAt(j) - '0');
}
}
String product = new String();
for (int i=0; i<m.length; i++) {
int digit = m[i] % 10;
int carry = m[i] / 10;
if (i+1 < m.length) {
m[i+1] = m[i+1] + carry;
}
product = digit + product;
}
while (product.length() > 1 && product.charAt(0) == '0') {
product = product.substring(1);
}
if (x.charAt(0) == '-' && y.charAt(0) != '-') {
product = new StringBuffer(product).insert(0, '-').toString();
}
else if (x.charAt(0) != '-' && y.charAt(0) == '-') {
product = new StringBuffer(product).insert(0, '-').toString();
}
else if (x.charAt(0) == '-' && y.charAt(0) == '-') {
product = product;
}
System.out.println("The multiplication of\n" + x + " \nand\n" + y + " " + "\nis\n" + product);
scan.close();
}
}
You're removing the negative symbol from the numbers here:
if (x.charAt(0) == '-' && y.charAt(0) != '-') {
x = x.substring(1);
}
else if (x.charAt(0) != '-' && y.charAt(0) == '-') {
y = y.substring(1);
}
So after those lines your x and y variables no longer contain the negative symbol.
So when you're checking it near the end here:
if (x.charAt(0) == '-' && y.charAt(0) != '-') {
product = new StringBuffer(product).insert(0, '-').toString();
}
else if (x.charAt(0) != '-' && y.charAt(0) == '-') {
product = new StringBuffer(product).insert(0, '-').toString();
}
else if (x.charAt(0) == '-' && y.charAt(0) == '-') {
product = product;
}
It will never get into any of the conditions.
One good way to debug this on your end is to set a breakpoint within the condition you think it should drop into and see if it's hit. Or breakpoint before the conditions and examine the variables to ensure they are what you expect them to be. You could also throw some println statements in there temporarily just to say "I got into this conditional".
The adjustment I'd recommend making is holding onto whether each number was negative before stripping the negative so you can use that in your logic later on.
Here's the adjustment which should accomplish what you want. I used Integers instead of bools to make the check for whether to apply the negative symbol later easier (i.e. isFirstNumberNegative + isSecondNumberNegative == 1)
Scanner scan = new Scanner(System.in);
System.out.println("Type the first number:");
String x = scan.nextLine();
System.out.println("Type the second number:");
String y = scan.nextLine();
// hold onto which numbers are negative
Integer isFirstNumberNegative = x.charAt(0) == '-' ? 1 : 0;
Integer isSecondNumberNegative = y.charAt(0) == '-' ? 1 : 0;
// strip the negative symbols from the numbers which are negative
if (isFirstNumberNegative > 0) {
x = x.substring(1);
}
if (isSecondNumberNegative > 0) {
y = y.substring(1);
}
String s1 = new StringBuffer(x).reverse().toString();
String s2 = new StringBuffer(y).reverse().toString();
int[] m = new int[s1.length() + s2.length()];
for (int i=0; i<s1.length(); i++) {
for (int j=0; j<s2.length(); j++) {
m[i+j] = m[i+j] + (s1.charAt(i) - '0') * (s2.charAt(j) - '0');
}
}
String product = new String();
for (int i=0; i<m.length; i++) {
int digit = m[i] % 10;
int carry = m[i] / 10;
if (i+1 < m.length) {
m[i+1] = m[i+1] + carry;
}
product = digit + product;
}
while (product.length() > 1 && product.charAt(0) == '0') {
product = product.substring(1);
}
// if only one number is negative put a negative symbol in front
// if both numbers are negative this condition won't hold true because it will be == 2
// if both numbers are positive this condition won't hold true because it wil be == 0
if (isFirstNumberNegative + isSecondNumberNegative == 1) {
product = new StringBuffer(product).insert(0, '-').toString();
}
System.out.println("The multiplication of\n" + x + " \nand\n" + y + " " + "\nis\n" + product);
scan.close();
Just remove the symbols from the numbers and save them. Then later, use them to determine if a negative is required. An exclusive or test for - is all that is necessary for a negative result.
You can create a record (or a class) to return the numbers and resulting sign, ready for processing.
record Numb(String sign,String num1, String num2) {}
String n1 = "-2123";
String n2 = "+2343";
Numb n = prepNums(n1,n2);
System.out.println(n.sign + ", " + n.num1 + " " + n.num);
Prints
-, 2123, 2343
After multiplying, just prepend the sign to the result. Note that the default positive sign is no sign.
And here is the method that processes the strings and returns
them and the resultant sign for multiplication.
public static Numb prepNums(String n1, String n2) {
boolean sign1 = false;
boolean sign2 = false;
char firstChar = n1.charAt(0);
if (!Character.isDigit(firstChar)) {
sign1 = firstChar == '-';
n1 = n1.substring(1); // remove sign
}
firstChar = n2.charAt(0);
if (!Character.isDigit(firstChar)) {
sign2 = firstChar == '-';
n2 = n2.substring(1); // remove sign
}
return new Numb( (sign1 ^ sign2) ? "-" : "", n1, n2);
}
just speaking in a generic concept sense - the square root of largest safe unsigned int,
4^3^3/2-1
is approx 94906265.6242. So right off the bat you know you don't have 8-full decimal digits width to work with unless you add in special tricks.
All those fancy algorithms they talk about - they frequently waste your time by having to first convert from decimal to binary, do the math, then re-convert it back out.
I just split mine into chunks of 7-digits wide, so the the maximum multiply result per op is capped at just shy of 10^14
- for 7 9's squaring each other, approx. 46.50699304-binary bits
- for 8 9's squaring ………. is approx. 53.15084949 bits
for whatever slowness one might believe in simpleton grade school multiply, you more than gain back the savings by avoiding a bidirectional base-conversion.
I should make a programm to control the number of an isbn 10 number. Therefore I'm not allowed to use arrays andd the input of the number has to be a char. The In method is similar to java scanner.
public class ISBN {
public static void main(String[] args) {
System.out.println("ISBN - Pruefung");
System.out.println("=================");
System.out.print("ISBN-Nummer: ");
char isbn = In.read();
int check = 0;
int d=0;
for (d=0; d<10; d++) {
if ('0' <= isbn && isbn <= '9' ) {
check = (int) ((isbn-48)*d)+check;
if(d ==9) {
int lastDigit = check%11;
if(lastDigit ==10) {
System.out.println("x");
}else {
System.out.println(lastDigit);
}
}else {
System.out.print(isbn);
}
}else {
System.out.println(isbn + "Falsche Eingabe");
System.exit(0);
}
isbn = In.read();
}
if (d == 10 && check%11 ==0) {
System.out.println("wahr");
}else {
System.out.println("falsch");
}
}
}
I googled some isbn 10 numbers but my programs says they are wrong (example 2123456802). Now my question where is my mistake and/or understood I the function of the last number wrong?
the sum of all the ten digits, each multiplied by its (integer) weight, descending from 10 to 1, is a multiple of 11.
So you just need to sum that digit value time the weight :
int check = 0;
for(int weight = 10; weight > 0; weigth--){
char c = In.read(); //get the next character
int i;
if( c == 'x' || c == 'X' ){
i = 10;
} else {
if(! Character.isDigit(c)) //Because, just in case...
throw new IllegalArgumentException("Not a numeric value");
i = Character.getNumericValue( c );
}
check += i * weight;
}
Just need to check if it is a multiple of 11
if ( check % 11 == 0 )
System.out.println( "VALID" );
else
System.out.println( "INVALID" );
I'm working on this program where I need to verify if every odd index in a String has the letter "X". For example if my String is: AXFXTX then I should get a message: "GOOD", if not I should get a message: "BAD". Can anyone tell me what I'm missing please. Thank you in advanced.
Here's my code
import java.util.Random;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int min = 1;
int max = 10;
int randomNum = rand.nextInt((max - min) + 1) + min;
System.out.println("Random number = " + randomNum);
System.out.print("Enter a word of " + randomNum + " characters:");
String myString = scan.nextLine();
while(myString.length() != randomNum){
System.out.print("Enter a word of " + randomNum + " characters:");
myString = scan.nextLine();
}
char[] c = myString.toCharArray();
for(int i = 0 ; i < c.length ; i++){
if(c[i] == 'X'){
System.out.println("GOOD!");
}
else{
System.out.println("BAD");
}
}
}
}
If I understand your question, then it's important to note that the first odd index is 1. So you can start at 3 and check if that, and every subsequent odd number (index += 2), is the same as the first. Something like,
boolean sameLetter = true;
for (int index = 3; index < c.length && sameLetter; index += 2) {
sameLetter = (c[1] == c[index]);
}
System.out.println(sameLetter ? "GOOD!" : "BAD");
Simply evaluate odd indices only:
char[] c = myString.toCharArray();
boolean good = true;
for(int i = 3 ; i < c.length ; i+=2){
if(c[i] != c[i-2]){
good = false;
break;
}
}
if(good) System.out.println("GOOD");
else System.out.println("BAD");
I would simply use a regular expression here
str.matches(".(\\w)(.\\1)+") //true is GOOD
Try
booelan allGood = true;
for(int i = 2 ; i < c.length ; i = i + 2){
if(c[i] != c[0]){
allGood = false;
break;
}
}
To start with, you need a boolean variable here to track if it's consistent across all characters. Second, you need to improve your loop
boolean testSucceed = true;
for(int i = 1 ; i < c.length ; i += 2){
if (c[i] != 'X') testSucceed = false;
break;
}
if(testSucceed){
System.out.println("GOOD!");
} else{
System.out.println("BAD");
}
Change the for loop to :
for(int i = 0 ; i < c.length ; i+=2)
so that it goes over alternate characters.
//If NOT divisible by 2- Check only ODD number
Edited: You are suppossed to use modulus % and not division %. My bad
for(int i = 0 ; i < c.length ; i++){
if(c[i]%2 != 0){
if(c[i] == 'X'){
System.out.println("GOOD!");
}
else{
System.out.println("BAD");
}
}
}
I am trying to make a java program that will allow the user to enter any amount of numbers. If they enter a 0, the program will say the tree is false. I got that to work but I want it so if the last two numbers entered have are 0 the program will print true. The 0 represents null
For example if they enter 5 numbers:
2 4 5 0 0 = true
2 0 5 0 0 = false
2 4 5 6 7 = true
All that other stuff was confusing so I simplified it
System.out.println("Enter a number or enter 0 to represent null: ");
for(int i=0;i<num;i++)
{
arr[i] = input.nextInt();
if(arr[i] == 0)
{
isTree = false;
}
}
System.out.println("Is this a tree: " + isTree);
You can use regex "[1-9]+0{2}" => one or more number between 1 to 9 and finish with 2 zero.
Example with your code :
System.out.println("Enter a number or enter 0 to represent null: ");
java.util.regex.Pattern pattern = Pattern.compile("[1-9]+0{2}");
java.util.regex.Matcher matcher = pattern.matcher("20500");
boolean isTree = false;
while(matcher.find()) {
isTree = true;
}
System.out.println("Is this a tree: " + isTree);
You can try this tool for test your regex : https://www.debuggex.com/
Do what you are doing, but also check for two zeros at the end:
System.out.println("Enter a number or enter 0 to represent null: ");
for(int i=0;i<num;i++)
{
arr[i] = input.nextInt();
if(arr[i] == 0 && i < arr.length-2) //ignore if last two nodes
{
isTree = false;
}
}
boolean isTree2 = (arr[arr.length-1] == 0 && arr[arr.length-2] == 0)
|| (arr[arr.length-1] != 0 && arr[arr.length-2] != 0);
System.out.println("Is this a tree: " + (isTree && isTree2));
I think you want that if last two digits are zero then your program will say its true.
int length = arr.length;
boolean isTree = false;
if(length >= 2) {
if(arr[length-1] == 0 && arr[length-2] == 0) {
isTree = true;
}
}
System.out.println(isTrue);
System.out.println("Enter a number or enter 0 to represent null: ");
boolean cond = false;
for(int i=0;i<num;i++){
arr[i] = input.nextInt();
if(arr[i] == 0){
cond = true;
}
if(arr[i] !=0 && cond){
isTree = true;
break;
}
}
System.out.println("Is this a tree: " + isTree);
I wouldn't bother checking as you're entering input, but check after all inputs have been made. I would concatenate all your inputs into a string and then evaluate the string to determine if it satisfies your tree condition.
public static void main(String[] args) throws Exception {
int num = 5;
int[] arr = new int[num];
System.out.println("Enter a number or enter 0 to represent null: ");
for (int count = 0; count < 5; count++) {
for (int i = 0; i < num; i++) {
arr[i] = input.nextInt();
}
// Arrays.toString(arr) results in [2, 4, 5, 0, 0]
// Remove all brackets, commas, and spaces
String inputs = Arrays.toString(arr).replaceAll("\\[", "").replaceAll("\\]", "").replaceAll(", ", "");
boolean isTree = true;
// Only have to check for ending 00 if you know a 0 is in your inputs
if (inputs.contains("0")) {
isTree = inputs.endsWith("00") && !inputs.substring(0, inputs.length() - 2).contains("0");
}
System.out.println("Is this a tree: " + isTree);
System.out.println("");
}
}
Results:
I had an interview in which I did terribly. So, now I'm trying to find the solution to the question. Here is the interview question:
"We have the following mapping:
M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1.
And we have the following rules:
Each letter maps to a positive integer value
You add the values together, except...
...when a value (or runs of the same values) is followed by a greater value, you subtract the total of that run of values.
Examples:
IIX -> 8
MCCMIIX -> 1808
We are given this Java method: int valueOfRoman(char roman).
We have implement the Java method: int romanToInt(String s)"
I know it is not a proper roman number system, but that is the actual question.
I was able to code a working solution to a proper Roman system. But I'm unable to change it so that it adapts to these new rules, particularly Rule 3. I have tried, but with no success. The way my solution is right now, for IIX, it prints 10, instead of the correct answer of 8. Here is my code (I also implemented valueOf for my testing):
static int romanToInt(String s) {
char curr;
int currVal;
char prev;
int prevVal;
int total = valueOfRoman(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
curr = s.charAt(i);
currVal = valueOfRoman(curr);
prev = s.charAt(i-1);
prevVal = valueOfRoman(prev);
total += currVal;
if(currVal > prevVal) {
total = total - (2*prevVal);
}
}
return total;
}
static int valueOfRoman(char c) {
if (c == 'M') {
return 1000;
} else if (c == 'D') {
return 500;
} else if (c == 'C') {
return 100;
} else if (c == 'L') {
return 50;
} else if (c == 'X') {
return 10;
} else if (c == 'V') {
return 5;
} else if (c == 'I') {
return 1;
}
return -1;
}
Any help is really appreciated. Specially useful would be if you can tell me how to modify my code. Thanks!
EDIT: I edited the names of the methods so they are clearer.
My take - works with the admittedly small tests you supplied.
static int rom2int(String s) {
if (s == null || s.length() == 0) {
return 0;
}
// Total value.
int total = 0;
// The most recent.
char current = s.charAt(0);
// Total for the current run.
int run = valueOf(current);
for (int i = 1; i < s.length(); i++) {
char next = s.charAt(i);
int value = valueOf(next);
if (next == current) {
// We're in a run - just keep track of its value.
run += value;
} else {
// Up or down?
if (value < valueOf(current)) {
// Gone down! Add.
total += run;
} else {
// Gone UP! Subtract.
total -= run;
}
// Run ended.
run = valueOf(next);
}
// Kee track of most recent.
current = next;
}
return total + run;
}
private void test(String s) {
System.out.println("Value of " + s + " = " + rom2int(s));
}
public void test() {
test("IVX");
test("IIVVL");
test("IIX");
test("MCCMIIX");
test("MVVV");
}
prints
Value of IVX = 4 - Odd!!!
Value of IIVVL = 38
Value of IIX = 8
Value of MCCMIIX = 1808
Value of MVVV = 1015
Here's how I'd approach the problem:
Read the string character by character and during every step note the current character and the previous character.
If the current character is the same as the previous, increase the run length by 1.
If the current character has a smaller value than the previous, add run length * value of previous character to the total, and reset run length to 1.
If the current character has a greater value than the previous, subtract run length * value of previous character from the total, and reset run length to 1.
So, nobody caught my hint. Then I'll give it a try, too. I won't go into the "IVX"- thing because I consider that a syntax error.
int romanToInt( String s ){
int total = 0;
int pivot = 0;
for( int i = s.length()-1; i >= 0; i--){ // We start at the **end**
int current = valueOfRoman((s.charAt(i));
if( current >= pivot ){ // We will have at least "I", so it **will** be > pivot for 1st char.
pivot = current;
total += pivot;
}else{
total -= current;
}
}
return total;
}
Let's see: IIX
i char value total pivot -> total pivot
2 X 10 0 0 > 10 10
1 I 1 10 10 < 9 10
0 I 1 9 10 < 8 10
MCCMIIX
i char value total pivot -> total pivot
6 X 10 0 0 > 10 10
5 I 1 10 10 < 9 10
4 I 1 9 10 < 8 10
3 M 1000 8 10 > 1008 1000
2 C 100 1008 1000 < 908 1000
1 C 100 908 1000 < 808 1000
0 M 1000 808 1000 = 1808 1000
The method leaves out input validation for brevity. I am assuming all input has been checked and consists only of allowed characters according to "the rules".
My take on it.
EDIT CHANGE #2
public class Romans {
private int valueOf(char c) {
if (c == 'M') {
return 1000;
} else if (c == 'D') {
return 500;
} else if (c == 'C') {
return 100;
} else if (c == 'L') {
return 50;
} else if (c == 'X') {
return 10;
} else if (c == 'V') {
return 5;
} else if (c == 'I') {
return 1;
}
return 0;
}
public int rom2int(String s) {
int currVal;
int runValue = 0;
int repetition = 0;
int total = 0;
boolean alreadyAdded = false;
for (int i = 0; i < s.length(); i++) {
currVal = valueOf(s.charAt(i));
if (runValue == 0) {
runValue = currVal;
repetition = 1;
alreadyAdded = false;
} else if (currVal > runValue) {
total = total + (currVal - (runValue * repetition));
repetition = 1;
runValue = currVal;
alreadyAdded = true;
} else if (currVal < runValue) {
if(!alreadyAdded) {
total += (runValue * repetition);
}
repetition = 1;
runValue = currVal;
alreadyAdded = false;
} else {
repetition++;
alreadyAdded = false;
}
}
if (!alreadyAdded) {
total += (runValue * repetition);
}
return total;
}
}
And the main I'm running:
public static void main(String[] args) {
Romans r = new Romans();
String[] inputs = {"MVVV", "IIX","MCCMIIX", "IVX"};
for(String input : inputs) {
System.out.println("Value of " + input + " is: " + r.rom2int(input));
}
}
Outputs:
Value of MVVV is: 1015
Value of IIX is: 8
Value of MCCMIIX is: 1808
Value of IVX is: 9
That's how I did.
It works for those 2 values you mentioned (IIX = 8 and MCCMIIX = 1808):
public static int rom2int(String s)
{
int currVal = 0, prevVal = 0, subTotal = 0, total = 0;
for (int i = 0; i < s.length(); i++) {
currVal = valueOf(s.charAt(i));
if (currVal > 0) {
if (prevVal == 0) {
subTotal = currVal;
}
else if (currVal > prevVal) {
total += (currVal - subTotal);
subTotal = 0;
}
else if (currVal < prevVal) {
total += subTotal;
subTotal = currVal;
}
else if (currVal == prevVal) {
subTotal += currVal;
}
prevVal = currVal;
}
}
total += subTotal;
return total;
}
public static int valueOf(char c)
{
if (c == 'M')
return 1000;
if (c == 'D')
return 500;
if (c == 'C')
return 100;
if (c == 'L')
return 50;
if (c == 'X')
return 10;
if (c == 'V')
return 5;
if (c == 'I')
return 1;
return 0;
}
EDIT 1:
Explanation for "IVX" value:
"...add values together except when a value (or runs of the SAME
values) is followed by a greater value, you subtract the total of that
run of values."
IVX = 1 5 10
if 5 > 1 then 5 - 1 = 4
if 10 > 5 then 10 - 0(*) = 10 (*) we already have used V(5) before, so we discard it.
So the answer for IVX is 14!
My approach would be to break the problem into the following steps:
Create a map of the symbols and values (a roman map).
Create a store to keep your result.
Loop through all the strings from RTL.
For each symbol, check that the value of the current symbol is greater than its previous value.
If the current symbol is greater than its previous value (e.g IV, where V is the current symbol), then do subtraction (current value minus previous value) and add that to the result; then skip the previous value in the loop.
Else; add the value of the current symbol to the result.
Note:
An important rule to note is that there can only be 1 prev value in the roman numerals to indicate a reduction.
IV = 4
IIV = invalid
...same with the rest of the numerals (IXCVDM...).
Hope this helps someone in the future.
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
romanMap = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 }
result = 0;
index = len(s) - 1;
while (index >= 0):
romanValue = s[index];
prevValue = s[index - 1];
if ((index > 0) and (romanMap[romanValue] > romanMap[prevValue])):
result += romanMap[romanValue] - romanMap[prevValue];
index-= 1;
else:
result += romanMap[romanValue];
index-= 1;
return result;
You can run the code with the following:
print(Solution().romanToInt("LVIII"));
this kind of problematics are usually really easy to solve using recursive way of thinking. The solution could look like :
public int rom2int(String s)
{
if(s.length() == 0)
// no string --> 0
return 0;
else if(s.length() == 1)
// One Character --> Value of Character
return valueOf(s.charAt(0));
else if((valueOf(s.charAt(0)) > valueOf(s.charAt(1))) )
// The value is NOT followed by a greater value --> We had the value
return rom2int(s.substring(1, s.length())) + valueOf(s.charAt(0));
else if(valueOf(s.charAt(0)) <= valueOf(s.charAt(1)) )
// The value is followed by a greater (or same) value --> We substract the value
return rom2int(s.substring(1, s.length())) - valueOf(s.charAt(0));
else
// Shouldn't Happen. 0 as neutral element in in a Sum.
return 0;
}
Even if recursive solution is forbidden, to my mind it is simpler to un-recursive this algorithm than find the procedural one at first try =)
Edit :
MY Results :
Value of MCCMIIX is : 1808
Value of IIX is : 8
Value of IVX is : 4
Value of IIVVL is : 38