C language course experience (4)

example:

1. Exchange the values ​​of the two variables a and b without using additional variables.
(1) Addition and subtraction:
#include <stdio.h>
int main()
int a=3;
int b=5;
a =a+b;
b=ab;//The original a is assigned to the current b
a=ab;//The original b is assigned to the current a
return 0;
}
Problem: Integer overflow, that is, the value obtained by a+b is possible Exceed the maximum limit of integer
(two) XOR method:
#include <stdio.h>
int main()
int a=3; 0011
int b=5; 0101
a=a^b; a=0110
b=a^b ; b=0011
a=a^b; a=0101
return 0;
}There
will be no overflow at this time because there will be no carry.
Generally, the third variable method is used in the enterprise, and the code is readable and efficient.
2. Given a non-empty integer array, except for an element that appears only once, every other element appears twice, and find the element that appears only once.
Example: int a[]={1,2,3,4,5,1,2,3,4}; Only 5 appears once in the array, and the rest appear in pairs. Find out 5.
Idea:
Two nesting counts the number of occurrences of each number, and output if the number is 1.
Violent solution method:
specific code:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int main(){
int arr[] = {1,2,3,4,5,1,2,3,4};
int i,p;
int count;
for (i = 0; i <= 8; + +i){
count = 0;
for (p = 0; p <= 8; ++p){
if (arr[i] == arr[p]){
count += 1;
}
}
if (count == 1){
printf("%d", arr[i]);
}
}
return 0;
}
Clever XOR method:
first:
a^a=0 0^a=a
a^b^a=ba^a^b =b (exclusive OR has commutative law)
so 1^2^3^4^5^1^2^3^4=1^1^2^2^3^3^4^4^5=5
can be found The
specific code of the number that
placed the order : #define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int main(){
int arr[] = {1,2,3,4,5,1,2,3,4};
int i;
int sum = arr[0];
for (i = 1; i <= 8; ++i){
sum = sum^arr[i];
}
printf("%d\n", sum);
return 0;
}
Time complexity: O(n)
but multiple single values ​​will not work
3 Write a shutdown program
program to run, your computer shuts down in 1 minute, if you enter: I am a pig, cancel the shutdown. In the
system, enter shutdown -s -t 60 (shutdown after 60 seconds) for the shutdown command
and shutdown -a is to cancel the shutdown command in
C language system("shutdown -s -t 60");
cancel using system("shutdown -a");
system needs to introduce #include <stdlib.h>

strcmp function

Usage:
strcmp (of arr1, arr2 is)
strcmp (ARR, "abc") array is abc If the function returns 0 returns a positive number when the former is greater than the return is less than the plurality of front
function need to add header #include <string.h>
specific function :
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char arr[] = "";
//system("shutdown -s -t 60 ");
again:
printf("Your computer is going to shutdown in 60s do something:");
scanf("%s", arr);
if (strcmp(arr,"pig")==0)
{
//system ("shutdown -a");
printf("ok");
}
else
{
goto again;
}
return 0;
}

Guess you like

Origin blog.51cto.com/15079723/2589169