How to separate and rotate numbers in integer?

30
October 14, 2021, at 00:00 AM

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

Answer 1

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
READ ALSO
How to auto move active class before after in JavaScript

How to auto move active class before after in JavaScript

I have created simple scroll animation page, if I scroll right side want to delete previous items

34
Unexpected performance degradation in unpickled set in python

Unexpected performance degradation in unpickled set in python

Set operations of a separately pickled objects are significantly slower than set operations of normal objects, or jointly pickled object

44
How to set class name to child element of a wrapper element?

How to set class name to child element of a wrapper element?

Above is the block where an image component is being called

12
mysql Trigger update table

mysql Trigger update table

Trigger Triggername afhentet Tabel scan After Insert

59