Home > Net >  How to separate and rotate numbers in integer?
How to separate and rotate numbers in integer?

Time:10-13

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

I have this simple int:

int birth = 011112;

and i want output looks 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 cycles? THX xoxo

CodePudding user response:

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(""   type   "."    type   "."   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
  •  Tags:  
  • java
  • Related