Search code examples
javahexoctal

What would be a octal to hex test case that would fail the following program?


I am trying to write a program that takes in a non negative octal number with a max of 8 to the 200000 power. The input will not have any leading zeroes, and the output must not contain any extra leading zeroes. I cannot think of a test case that this would fail, but it certainly does not go through as the correct answer. Hence, I am missing an edge case, I wonder which one. I am aware that there are some "leading zeroes" problems that could be encountered during this conversion, but I do not fully understand what it entails, hence am not able to see the problem / come up with a solution for it.

import java.util.*;
import java.io.*;

public class arithmetic{
    public static void main(String[] args) throws Exception{
        InputStreamReader ir = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(ir);
        String octal = br.readLine();
        if(octal == null){
            System.out.println("0");
            return;
        }

        long decimal = Long.parseLong(octal,8);
        System.out.println(Long.toHexString(decimal).toUpperCase());

    }
}

Solution

  • Try an octal number with lots and lots of digits. Your input can have up to 2000000. A Java Long is only a 64-bit signed number.

    You can’t put a big-enough octal number into any Java basic type, so you need a completely different approach.

    One way would be to read groups of 8 octal digits (24 bits) and convert them to groups of 6 hex digits.

    Or check out this answer for more on BigInteger and BigDecimal.