2

so there was a problem I had in implementing a program (given below). The problem occurs when I pass num = 1006, the private method returns "MVI", but the public method returns "M". Could anyone explain this?

public class Solution {
    public String intToRoman(int num) {
       String j = intToRoman(num, "");
       return j;
    }

private String intToRoman(int num, String s) {
    //String s = "";
    if (num >= 1000) {
        s += 'M';
        num -= 1000;
        intToRoman(num, s);
    } else if (num >= 500) {
        s += 'D';
        num -= 500;
        intToRoman(num, s);
    } else if (num >= 100) {
        s += 'C';
        num -= 100;
        intToRoman(num, s);
    } else if (num >= 50) {
        s += 'L';
        num -= 50;
        intToRoman(num, s);
    } else if (num >= 10) {
        s += 'X';
        num -= 10;
        intToRoman(num, s);
    } else if (num >= 5) {
        s += 'V';
        num -= 5;
        System.out.println("Checkpoint 1");
        System.out.println(s);
        intToRoman(num, s);
    } else if (num >= 1) {
        s += 'I';
        num -= 1;
        System.out.println("Checkpoint 2");
        intToRoman(num, s);
    } else {
        System.out.println("Returning "+ s);
        return s;
    }
    return s;
}
2
  • 1
    You might want to return intToRomain(num, s);. Commented Nov 9, 2016 at 8:25
  • use StringBuilder if you don't want re-assigned value s Commented Nov 9, 2016 at 8:37

1 Answer 1

2

intToRoman(num, s) doesn't change the value of s, since Java is a pass by value language.

You should replace each

intToRoman(num, s);

with

s = intToRoman(num, s);

in order for s to be assigned a new value.

The alternative is to return intToRoman(num, s) instead of s.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.