35行C++代碼實現時間戳轉時間算法

程序邏輯概述

根據平年閏年計算規則,利用遞歸先求出年份。之後再根據固定的大小月規則和平年閏年下2月天數的不同求出月數,之後就剩下最簡單的天數、小時、分鐘和秒了。

這個程序我承認為了儘可能縮小行數,有的地方寫的不是很規範~正可謂是為了減少行數而不擇手段~

程序代碼

注:去掉空行的話的確只有35行的,我並不是標題黨!

#include <iostream>

int time_stamp = 28800, year = 1969, month = 0, day = 0, hour = -1, minute = -1, tmp;

auto isLeapYear = [] { return (year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0) || (year % 3200 == 0 && year % 172800 == 0); };

int getYear(int *ptr_time_stamp) {
	++year;
	if (*ptr_time_stamp >= (isLeapYear() ? 31622400: 31536000))
		getYear(&(*ptr_time_stamp -= (isLeapYear() ? 31622400 : 31536000)));

	return year;
}

int getMonth(int *ptr_time_stamp) {
	++month;
	if (month == 2 && (*ptr_time_stamp >= (isLeapYear() ? 2505600 : 2419200)))
		getMonth(&(*ptr_time_stamp -= (isLeapYear() ? 2505600 : 2419200)));
	else if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && *ptr_time_stamp >= 2592000)
		getMonth(&(*ptr_time_stamp -= 2678400));
	else if ((month == 4 || month == 6 || month == 9 || month == 11) && *ptr_time_stamp >= 2678400)
		getMonth(&(*ptr_time_stamp -= 2592000));

	return month;
}

int getTime(int *ptr_time_stamp, int *type, int second) {
	++*type;
	if (*ptr_time_stamp >= second) 
		getTime(&(*ptr_time_stamp -= second), type, second);

	return *type;
}

int main(void) {
	std::cin >> tmp;
	time_stamp += tmp;

	std::cout << getYear(&time_stamp) << "年";
	std::cout << getMonth(&time_stamp) << "月";
	std::cout << getTime(&time_stamp, &day, 86400) << "日 ";
	std::cout << getTime(&time_stamp, &hour, 3600) << "時";
	std::cout << getTime(&time_stamp, &minute, 60) << "分" << time_stamp << "秒";

	return 0;
}

利用位運算求數字的補數

題目

給定一個正整數,輸出它的補數。補數是對該數的二進制表示取反。

注意

1.給定的整數保證在32位帶符號整數的範圍內。
2.假定二進制數不包含前導零位。

解題思路

求出一個與輸入數字在二進制位的數量上相同,且每位都為1的數字,之後利用該數字和輸入的數字做異或操作,即可得出補數。

例如

2的二進制為10,和他二進制位數相同,且全為1的十進制數為3,即二進制11。2與3做異或操作,得到二進制01,這也就是2的補數1。

代碼

#include <stdio.h>

int main(void)
{
    int in = 0;
    int tmp = 1;

    scanf("%u", &in);

    // 不斷將tmp左移並在末尾填充1,當tmp的位數與in相同時tmp大於in,循環終止。
    while (tmp < in) {
        tmp <<= 1;
        tmp += 1;
    }

    printf("%u\n", tmp ^ in);
}