C language corner overtaking must do a good collection of questions (programming questions)

Table of contents

Foreword:

1. Calculate date to day conversion

2. Nicoches Theorem 

3. Password check

4. Picture arrangement

5. Find the center subscript of the array

6. Statistics of the number of characters

7. Most elements


Foreword:

If you want to learn programming well, you need to learn more questions. We not only need to do more questions, but also do well! For this reason, I started a series of must-do questions for cornering and overtaking. This is the first programming question, and each article has about 5 questions. This series will be updated from time to time, so stay tuned!


1. Calculate date to day conversion

describe

Based on the date entered, the calculation is the day of the year.

The year is guaranteed to be 4 digits and the date is legal.

Advanced: Time Complexity: O(n), Space Complexity: O(1) 

Enter a description:

Enter one line, each line is separated by spaces, which are year, month, and day

Output description:

The output is the day of the year

#include<stdio.h>
int main()
{
    int arrmonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int year, month, day;
    scanf("%d %d %d", &year, &month, &day);

    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
        arrmonth[1]++;
    int i = 0;
    for (i = 0; i < month - 1; i++) 
    {
        day = day + arrmonth[i];
    }
    printf("%d", day);
    return 0;
}

Ideas:

1. Judgment method of leap year

(1) Divisible by 4 but not by 100;

(2) Divisible by 400.

2. The number of days in each month

One, three, five, seven and eighty days are 31 days, February, 29 days in leap years, 28 days in normal years, and 30 days in other months

3. Calculate the number of days in n-1 months before the month, plus the number of days in this month


2. Nicoches Theorem 

describe

Verify the Nicorches theorem, that is: the cube of any integer m can be written as the sum of m consecutive odd numbers.

For example:

1^3=1

2^3=3+5

3^3=7+9+11

4^3=13+15+17+19

Input a positive integer m (m≤100), write the cube of m as the sum of m consecutive odd numbers and output.

Enter a description:

Enter an int integer

Output description:

output decomposed string

#include<stdio.h>
int main()
{
	int n = 0, i = 0; char str[1000];
	while (scanf("%d", &n) == 1)
	{
		int x = n + (n - 1) * (n - 1);
		sprintf(str, "%d", x);
		for (i = 0; i <n-1 ; i++)
		{
			x += 2;
			sprintf(str, "%s+%d", str, x);		
		}
		puts(str);
	}
	return 0;
}

Parse:

What is the numerical value, there will be several odd numbers added.

1^3=1                                

2^3=3+5

3^3=7+9+11

4^3=13+15+17+19

It is not difficult to find that this is an odd arithmetic sequence {1, 3, 5, 7, 9...} starting from 1.

Therefore, as long as we know the number corresponding to the value, we can know any number to be added, and it conforms to the law.

like:

1^3=1                                                          1- >1                          1+(1-1)^2

2^3=3+5                                                      2- >3                          2+(2-1)^2

3^3=7+9+11                                                3- >7                         3+(3-1)^2

4^3=13+15+17+19                                     4- >13                        4+(4-1)^2

……

……                                                                                               n+(n-1)^2

If you are not familiar with the usage of sprintf, you can read this blogger's article. ( the 7th in the order read and write of the file )

C language file operation_WHabcwu's blog-CSDN blog Requirements: We want to record the information, only when we choose to delete the data, the data will cease to exist. This involves the problem of data persistence. Our general data persistence methods include storing data in disk files and storing them in databases. Using files, we can store data directly on the hard disk of the computer, achieving data persistence. 1.2. https://blog.csdn.net/WHabc2002/article/details/131755342


3. Password check

describe

Xiao Ming recently developed a website. When a user registers an account, he needs to set a password for the account. In order to strengthen the security of the account, Xiao Ming has certain requirements for the strength of the password:

1. The password can only be composed of uppercase letters, lowercase letters and numbers;

2. The password cannot start with a number;

3. At least two of the three character types of uppercase letters, lowercase letters and numbers appear in the password;

4. Password length should be at least 8

Now Xiao Ming has received n passwords, and he wants you to write a program to judge which of these passwords are suitable and which are illegal.

Enter a description:

Enter a number n, followed by n (n ≤ 100) lines, each line has a string representing a password, and the input guarantees that only uppercase letters, lowercase letters and numbers appear in the string, and the length of the string does not exceed 100.

Output description:

Input n lines, if the password is valid, output YES, if not, output NO

analyze:

This question only needs to count each character (uppercase characters, lowercase characters, numbers, other characters) of the string from the beginning to the end. Then judge whether the conditions are met one by one. The conditional judgment includes:
length not less than 8
cannot start with a number
Can only contain letters and numbers
Case and character must have two or more

Look directly at the code:

#include<stdio.h>
#include<ctype.h>
#include<assert.h>
#include<string.h>
int f(char* arr)
{	    
	    assert(arr);
	    int i = 0;
		int sz = strlen(arr);
		if (sz < 8)
		{
			return 0;
		}
		if (arr[0] >= '0' && arr[0] <= '9')
		{
			return 0;
		}
		int* count = (int*)calloc(3, sizeof(int));
		for (i = 0; i < sz; i++)
		{
			
			if (arr[i] >= '0' && arr[i] <= '9')
			{
				count[0] = 1;
			}
			else if (islower(arr[i]))
			{
				count[1] = 1;
			}
			else if (isupper(arr[i]))
			{
				count[2] = 1;
			}
			else
			{
				free(count);
				return 0;
			}
		}
		if ((count[0] + count[1] + count[2] )>= 2)
		{
			free(count);
			return 1;
		}
		else
		{
			free(count);
			return 0;
		}

}
int main()
{
	char arr[101] = { 0 };
	int n=0;
	scanf("%d", &n);
	while (n)
	{
		scanf("%s", arr);
		n--;
		int x=f(arr);
		if (x == 1)
		{
			printf("YES\n");
		}
		else
		{
			printf("NO");
		}
	}
	
	return 0;
}

4. Picture arrangement

describe

 Enter a description:

 Output description:

 

 code:

#include<stdio.h>
#include<string.h>
int main()
{
	char arr[1000];
	gets(arr);
	int i = 0, j = 0;
	for (i = 0; i < strlen(arr) - 1; i++)
	{
		for (j = 0; j < strlen(arr) - 1 - i;j++)
		{
			if (arr[j] > arr[j + 1])
			{
				char t = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = t;
			}
		}
	}
	puts(arr);
	return 0;
}
[Answer analysis]:
This question is actually about character sorting. Each ascii character has a corresponding ascii value in the memory, and it can be sorted by storing the data in the memory.
Bubble sorting: compare and exchange adjacent data, push the larger or smaller data back to the end of the array, and then start the next round of bubbling process of big data.

5. Find the center subscript of the array

Find the central subscript of the array https://leetcode.cn/problems/find-pivot-index/

#include<stdio.h>
int pivotIndex(int* nums, int numsSize) {
	int total = 0;
	int i = 0;
	int sum = 0;
	for (i = 0; i < numsSize; i++)
	{
		total += nums[i];
	}
	for (i = 0; i < numsSize; i++)
	{
		if (2 * sum + nums[i] == total)
		{
			return i;
		}
		sum += nums[i];
	}
	return -1;
}

Parse:

The sum of all the elements of the array arr is total, when the ith element is traversed, the sum of the left elements is sum,

Then the sum of the elements on the right is total−sum-arr[i], and the elements on the left and right are equal, that is, arr[i]+sum*2=total.


6. Statistics of the number of characters

 Idea: Create an array of size 128, mark the characters that have appeared, and then count the number of marks

#include<stdio.h>
#include<string.h>
int main()
{
	int arr[127] = { 0 };
	char str[500];
	gets(str);
	int i=0;
	int sz = strlen(str);
	int count = 0;
	for (i = 0; i < sz; i++)
	{
		if (arr[str[i]] == 0)
		{
			count++;
			arr[str[i]] = 1;
		}
	}
	
	printf("%d", count);
	return 0;
}

7. Most elements

Majority element https://leetcode.cn/problems/majority-element/

 Method 1: Array sorting method

Ideas:

If all the elements in the array nums are sorted in monotonically increasing or monotonically decreasing order, then the element with subscript n/2
(subscript starts from 0) must be the majority.

int majorityElement(int* nums, int numsSize) {
	int i = 0, j = 0;
	for (i = 0; i < numsSize-1; i++)
	{
		for (j = 0; j < numsSize - 1; j++)
		{
			if (nums[j] < nums[j + 1])
			{
				int t = nums[j];
				nums[j] = nums[j + 1];
				nums[j + 1] = t;
			}
		}
	}
	return nums[numsSize / 2];
}

Because the time complexity of bubble sorting is O(n^2)

Method 2: Moore Voting

int majorityElement(int* nums, int numsSize){
int count = 1;
int tmp = nums[0];
for (int i = 1; i < numsSize; i++) {
if (tmp == nums[i]){//与保存的字符相同则计数+1
count++;
} else {//与保存的字符不同则计数-1
count--;
//计数为0表示有可能保存的字符不是最多的字符,换下一个
if (count == 0) tmp = nums[i + 1];
}
}
return tmp;
}
[Answer analysis]:
There is a number in an array that appears more than n/2 times , starting from the 0th character , assuming it is the number with the most numbers, counting +1 when encountering the same number, and counting -1 when encountering different numbers , in fact, they are mutual Consumption, when the count is 0 , it means that the mutual spelling is completed, and the spelling is restarted from the next character, but in the final analysis, the number of occurrences greater than n/2 is more, so it is also the last reserved character.
Example:
"23335" first counts 1 from character 2 , and if it encounters 3 , if it is different , it will be -1 , and the process of mutual consumption will start from the remaining "335" . At this time, the saved character is 3 , and when it encounters 3 , it will count +1 , When encountering 5 , count -1 , when the count is not 0 , the characters saved at the end are the characters whose number exceeds n/2


The above is my personal sharing, if you have any questions, welcome to discuss! !

I've seen this, why don't you pay attention and give a free like 

 

Guess you like

Origin blog.csdn.net/WHabc2002/article/details/131967336