221k views
4 votes
Given a 8-digit integer representing a date in the format YYYYMMDD, output the year, month, and day using the format YYY-MM-DD. Ex: If the input is: 20221225 the output is: 2022-12-25 Hint: Use % to get the desired rightmost digits. Ex: The rightmost 2 digits of 572 is gotten by 572%100, which is 72. Hint: Use // to shift right by the desired amount. Ex: Shifting 572 right by 2 digits is done by 572 // 100, which yields 5. (Recall integer division discards the fraction). For simplicity, assume any part starts with a non-zero digit. So 0119998888 is not allowed.

User Dontcare
by
7.9k points

1 Answer

2 votes

Final answer:

To convert an 8-digit integer representing a date in the format YYYYMMDD to the format YYY-MM-DD, you can extract the year, month, and day components using the modulo and integer division operators. For example, if the input is 20221225, the output is 2022-12-25.

Step-by-step explanation:

To convert an 8-digit integer representing a date in the format YYYYMMDD to the format YYY-MM-DD, we can use the following steps:

  1. Extract the year component by performing integer division by 10000. For example, if the input is 20221225, the year component is obtained by 20221225 // 10000, which equals 2022.
  2. Extract the month component by performing integer division by 100 and then taking the remainder using the modulo operator. For example, if the input is 20221225, the month component is obtained by (20221225 // 100) % 100, which equals 12.
  3. Extract the day component by taking the remainder using the modulo operator. For example, if the input is 20221225, the day component is obtained by 20221225 % 100, which equals 25.

Therefore, for the input 20221225, the output is 2022-12-25.

Learn more about converting an 8-digit integer representing a date to the format yyyy-mm-dd here:

User Iamdto
by
8.4k points