Skip to content
Advertisement

How to separate and rotate numbers in integer? [closed]

I have a small problem. I think it’s simple, but I don’t know, how to manage it properly.

I have this simple int:

int birth = 011112;

and I want output to look like this, in this specific format.

"Your birth date is 12.11.01."

I did it with an integer array, but I want only one integer input like this one, not an array.

Could some body help me? Is there any simple method to manage it of, without using loops?

Advertisement

Answer

Basically, the conversion of the int representing a date in some format into String should use divide / and modulo % operations, conversion to String may use String.format to provide leading 0.

The number starting with 0 is written in octal notation, where the digits in range 0-7 are used, so the literals like 010819 or 080928 cannot even be written in Java code as int because of the compilation error:

error: integer number too large
    int birth = 010819;

However, (only for the purpose of this exercise) we may assume that the acceptable octal numbers start with 01 or 02 then such numbers are below 10000 decimal.

Then the numeric base for division/modulo and the type of output (%d for decimal or %o for octal) can be defined:

public static String rotate(int x) {
    int    base = x < 10000 ? 0100 : 100;
    String type = x < 10000 ? "o" : "d";
    int[] d = {
        x % base,
        x / base % base,
        x / (base * base)
    };
    return String.format("%02" + type + ".%02" +  type + ".%02" + type, d[0], d[1], d[2]);
}

Tests:

System.out.println(rotate(011112)); // octal
System.out.println(rotate(11112));  // decimal (no leading 0)

Output:

12.11.01
12.11.01
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement