3

Since this is homework, I can't use built-in functions. I have to use algorithms in Java.

This is what I have so far but it is wrong.

import java.util.Scanner;

public class ChangingFigures {
    public static void main (String[] args){
        Scanner scanner = new Scanner (System.in);
        System.out.print("Enter an integer between 0 and 127:");

        int num = scanner.nextInt ();

        String hex = Integer.toHexString(num);
        String bin = Integer.toBinaryString(num); 
        // ...
    }
}
2
  • seems to work fine for me, what problem are you running into? Commented Jun 21, 2011 at 13:32
  • I can't use built in functions. Commented Jun 21, 2011 at 13:33

2 Answers 2

7

The algorithm is trivial:

make an empty string
do:
    prepend "n" modulo "base" to that string
    divide "n" by "base"
until (n == 0)

if "base" is greater than 10 you'll need to do a little work to convert the "digits" into the letters that represent 10+

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

4 Comments

+1 for providing pseudocode instead of just giving the answer (as well as the algo being right, of course). Very nicely done.
While it doesn't matter since user808520 seems to be using Java, the div function in the C standard library would actually be pretty nice for this sort of thing, as it allows you to calculate the modulo value in the same step as the division.
@JAB yes, if performance were an issue then calculating the division and remainder at the same time would be optimal.
Well, there's that, but I was speaking more generally. It's not just the performance but the way the code looks. On the other hand the usage of div could potentially be confusing to those who don't know the standard library that well, so it's still a tradeoff despite the advantages.
-1

To HEX:

String HEXES = "0123456789ABCDEF";
System.out.println(HEXES.charAt((num & 0xF0) >> 4) + "" + HEXES.charAt((num & 0x0F)));

To binary

1 Comment

your magic-looking answer seems to be missing something, and doesn't get at the algorithm, or explain anything. if num is 256 it fails greatly.

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.