# C language simple program practice

Posted by dannau on Sat, 05 Mar 2022 06:44:02 +0100

# Square root of x

```int mySqrt(int x)
{
int low = 0, mid = 0, high = x;
if (x < 0)
return -1;
if (x <= 1)
return x;
while(low + 1 < high)
{
mid = low + (high - low) / 2;
if (x / mid < mid)
high = mid;
else
low = mid;
}
return low;
}
```

# Gemstones and stones

```int numJewelsInStones(char * J, char * S)
{
int num = 0;
for(int i = 0; S[i] != '\0'; i++)
{
if(strchr(J,S[i]))
num++;
}
return num;
}
```

# Guess the size of the number

```/**
* Forward declaration of guess API.
* @return 	     -1 if num is lower than the guess number
*			      1 if num is higher than the guess number
*               otherwise return 0
* int guess(int num);
*/

int guessNumber(int n)
{
if(guess(n) == 0)
return n;
int low = 1, high = n, mid;
while(low < high)
{
mid = (low + high) / 2;
int rest = guess(mid);
if(rest == 0)
return mid;
else
if (rest == 1)
low = mid + 1;
else
high = mid;
}
return low;
}
```

# Guess the correct number

```int game(int* guess, int guessSize, int* answer, int answerSize)
{
int count = 0;
for(int a = 0; a < guessSize; a++)
{
count++;
}
return count;
}
```

# Find a number in a two-dimensional array

```bool findNumberIn2DArray(int** matrix, int matrixSize, int* matrixColSize, int target)
{
if (matrix == NULL || matrixSize == 0 || matrixColSize == NULL || *matrixColSize == 0)
return false;
int i = 0, j = *matrixColSize - 1;
while (i < matrixSize && j >= 0)
if (matrix[i][j] == target)
return true;
else if (matrix[i][j] > target)
j--;
else
i++;
return false;
}
```

# raid homes and plunder houses

```int rob(int* nums, int numsSize)
{
int Ak, Ak_1, Ak_2;
int i;
if(numsSize == 0)return 0;
if(numsSize == 1)return nums[0];
if(numsSize == 2)return nums[0] > nums[1] ? nums[0] : nums[1];
Ak_2 = nums[0];
Ak_1 = nums[0] > nums[1] ? nums[0] : nums[1];
for(i = 2; i < numsSize; i++){
Ak = (Ak_2 + nums[i]) > Ak_1 ? Ak_2 + nums[i] : Ak_1;
Ak_2 = Ak_1;
Ak_1 = Ak;
}
return Ak;
}
```

# House raiding 2

```int rob(int* nums, int numsSize)
{
int a, b, temp;
if(numsSize == 0)
return 0;
if(numsSize == 1)
return nums[0];
if(numsSize == 2)
return nums[0] > nums[1] ? nums[0] : nums[1];
b = nums[0];
a = nums[0] > nums[1] ? nums[0] : nums[1];
for(int i = 2; i < numsSize; i++ )
{
temp = a;
a = b + nums[i] > a ? b + nums[i] : a;
b = temp;
}
return a;
}

//Before the beginning of each cycle, a stores the maximum value that can be stolen in the first i-1 room,
// b store the maximum value that can be stolen in the first i rooms
```

# Recursively find the Y power of X

```double Pow(double x,int y)
{
if(y==0)
return 1;
else
return(x*Pow(x,y-1));
}
```

# Non decreasing column

```bool checkPossibility(int* nums, int numsSize)
{
if (numsSize < 3)
{
return true;
}
int count = 0;
if (nums[0] > nums[1])
{
nums[0] = nums[1];
count++;
}

for (int i = 1; i < numsSize - 1; i++)
{
int right = nums[i+1];
if (nums[i] > right)
{
count++;
if (count > 1)
return false;
int left = nums[i-1];
if (left > right)
nums[i+1] = nums[i];
else
nums[i] = left;
}
}
return true;
}
```

# Fibonacci sequence

```int fib(int n)
{
if(n == 0)
return 0;
if(n == 1)
return 1;
int a = 0, b = 1, sum = 0;
for( int i = 1; i < n; i++ )
{
sum = (a + b) % 1000000007;
a = b;
b = sum;
}
return sum;
}
```

# and

```int *result = (int *)malloc(sizeof(int) * 2);
for (int i = 0; i < numsSize - 1; i++)
{
for (int j = i + 1; j < numsSize; j++)
{
if (nums[i] + nums[j] == target)
{
result[0] = i;
result[1] = j;
*returnSize = 2;
return result;
}
}
}
return result;
```

# Palindrome number

```bool isPalindrome(int x)
{
long s = 0;
int x1 = x;
while (x1 > 0)
{
s = s * 10 + x1 % 10;
x1 = x1 / 10;
}
return s == x;
}
```

# Number of steps to change the number to 0

```int numberOfSteps (int num)
{
int n=0;
while(num!=0)
{
if(num%2==0)
{
num=num/2;
n++;
}
else
{
num-=1;
n++;
}
}
return n;
}
```

# Zero after factorial

```int trailingZeroes(int n)
{
int res = 0;
// The number of 5 is n / 5 + n / 25 + n / 125
while (0 < n)
{
res += n / 5;
n /= 5;
}
return res;
}
```

# Roman numeral to integer

```int romanToInt(char * s)
{
int count = 0;
while (*s)
{
if (*s == 'V')
count += 5;
else if (*s == 'L')
count += 50;
else if (*s == 'D')
count += 500;
else if (*s == 'M')
count += 1000;
else if (*s == 'I')
count = (*(s + 1) == 'V' || *(s + 1) == 'X') ? count - 1 : count + 1;
else if (*s == 'X')
count = (*(s + 1) == 'L' || *(s + 1) == 'C') ? count - 10 : count + 10;
else
count = (*(s + 1) == 'D' || *(s + 1) == 'M') ? count - 100 : count + 100;
s++;
}
return count;
}
```

# Take a coin

```int minCount(int* coins, int coinsSize)
{
int sum = 0;
for(int i = 0; i < coinsSize; i++)
sum += (coins[i] + 1) / 2;
return sum;
}
```

# Euclidean algorithm (finding the greatest common divisor)

```#include<stdio.h>
int ComFactor(int m,int n);

int main()
{
int a,b;
scanf("%d%d",&a,&b);
printf("The maximum common divisor is:%d\n",ComFactor(a,b));
return 0;
}

int ComFactor(int m,int n)
{
int r=m%n;
while(r!=0)
{
m=n;
n=r;
r=m%n;
}
return n;
}
```

# Judge whether the single linked list is monotonically increasing

```#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

typedef int DataType; /*Define the data type of linear table, assuming int type*/
typedef struct Node /*Defines the node type of a single linked list*/
{
DataType data;
struct Node *next;
} Node;

int Judgelist(Node *first);

int main()
{
int a[5]={2,1,3,4,5};		//Sequence of judgment
Node*s=NULL,*r=NULL;
Node*first=(Node*)malloc(sizeof(Node));
r=first;
for(int i=0;i<5;i++)
{
s=(Node*)malloc(sizeof(Node));
s->data=a[i];
r->next=s;r=s;
}
r->next=NULL;

int x;
x=Judgelist(first);
if(x==1)
{
printf("It is monotonically increasing");
}
else
{
printf("Not monotonically increasing");
}
return 0;

}

int Judgelist(Node *first)
{
Node *p=first->next;
int flag;
while(p->next!=NULL)
{
if(p->data<p->next->data)
{
p=p->next;
flag=1;
}
else
{
flag=0;
break;
}
}
return flag;
}
```

# Judge whether two binary trees are similar

```typedef char DataType;
typedef struct BiNode
{
DataType data;
struct BiNode *lchild, *rchild;
}BiNode;

bool LikeTree( BiNode *b1, BiNode *b2 )
{
bool like1, like2;
if( b1 == NULL && b2 == NULL )
return true;
else
{
if( b1 == NULL || b2 == NULL )
return false;
else
{
like1 = likeTree(b1 -> lchild ,b2 -> lchild );
like2 = likeTree(b1 -> rchild ,b2 -> rchild );
return ( like1 && like2 );
}
}
}
```

# Sum of squares

```bool judgeSquareSum(int c)
{
for( int a = 0; a <= sqrt(c);a++)
{
double b = sqrt ( c - a * a );
if( b == (int)b )
return true;
}
return false;
}
```

# Seven bridge problem (Euler loop)

```#include<stdio.h>
int EulerCircuit(int mat[4][4],int n);	//Function declaration to find the number of vertices through the odd bridge

int main()
{
int mat[4][4]={{0,1,2,2},{1,0,1,1},{2,1,0,0},{2,1,0,0}};
int num=EulerCircuit(mat,4);			//Call the function to get the number of vertices through the odd bridge
if(num>=2)							//More than two vertices pass through an odd bridge
printf("have%d There are odd bridges in all places, and there is no Euler circuit\n",num);
else								//No top point leads to odd bridge
printf("Euler loop exists\n");
return 0;
}

int EulerCircuit(int mat[4][4],int n)	//Function definition, two-dimensional array as formal parameter
{
int i,j,degree,count=0;				//count the cumulative number of vertices passing through the odd bridge
for(i=0;i<n;i++)					//Accumulate the elements of each row in turn
{
degree=0;						//degree stores the number of bridges passing through vertex i and is initialized to 0
for(j=0;j<n;j++)
{
degree=degree+mat[i][j];	//Sum the number of bridges passing through vertex i
}
if(degree%2!=0)
count++;
}
return count;						//End the function and return count to the calling function
}
```

# Intimate string

```bool buddyStrings(char * A, char * B)
{
int i,j;
int count = 0, pos,
len1 = strlen(A), len2 = strlen(B);
if(len1 == 0 && len2 == 0)
return false;
int temp[3]={1,2,3};      //Record the subscript array of different characters, and set the starting value to be different
if(len1 != len2)
return false;
for(i = 0; i < len1;i++)
{
if(A[i] - B[i] != 0)
temp[count++] = i;			//Record different locations
if(count > 2)
return false;
}
if(count == 1)
return false;
if(count == 2 && A[temp[0]] == B[temp[1]] && A[temp[1]] == B[temp[0]])          //The two positions are different and equal to each other. Returns true
return true;
else if(count == 0)                                                         //Processing a and B are all equal. If there is a repetition, it returns true
{
for(i = 0; i < len1; i++)
{
for(j = i+1; j < len1; j++)	//Loop to determine whether there are equal numbers
{
if(A[i] == A[j])
return true;
}
}
}
return false;
}
```

# Frog jumping steps

```int numWays(int n)
{
int sum, i, a = 1, b = 2;
if(n == 0 || n == 1)
return 1;
if(n == 2)
return 2;
for(i = 2; i < n; i ++)
{
sum = ( a + b ) % 1000000007;
a = b;
b = sum;
}
return sum;
}
```

# Judge whether the single linked list is incremented

```//Design an algorithm to judge whether the single linked list is increasing
#include<stdio.h>
#include<stdlib.h>

typedef struct slist
{
int data;

struct slist *next;
}list;

list* creatlist();//Establishing single linked list by tail interpolation

int judgelist(list *l);//Judge whether the linked list is orderly

int main(void)
{
list *l = creatlist();

int x;

x = judgelist(l);

if(x == 1)
{
printf("It is monotonically increasing");
}

else
{
printf("Not monotonically increasing");
}

return 0;
}

list* creatlist()
{

l = (list *)malloc(sizeof(list));

l->next = NULL;

list *s;

list *r;//Tail pointer

r = l;//The tail pointer always points to the tail node

int x;

scanf("%d",&x);

while(x != 0)
{
s = (list *)malloc(sizeof(list));

s->data = x;

r->next = s;

r = s;//Tail pointer movement

scanf("%d",&x);
}

r->next = NULL;//Empty tail node

return l;
}

int judgelist(list *l)
{
list *p = l->next ;//Point to the first element node

int flag;

while(p->next  != NULL)
{
if(p->data < p->next->data )
{
p = p->next ;

flag = 1;
}

else
{
flag = 0;

break;
}
}

return flag;
}
```

# Replace spaces

```char* replaceSpace(char* s)
{
int n = 0;
for(int i = 0; s[i] != '\0'; ++i)
++n;
char* res;
res = (char*)malloc(3 * (n + 3) * sizeof(char));
int k = 0;
for(int i = 0; i < n; ++i)
{
if(s[i] != ' ')
res[k++] = s[i];
else
{
res[k++] = '%';
res[k++] = '2';
res[k++] = '0';
}
}
res[k] = '\0';
return res;
}
```

# Even statistics

```int findNumbers(int* nums, int numsSize)
{
int count = 0;
for(int i = 0; i < numsSize; i++)
{
if((nums[i] >= 10 && nums[i] < 100)||(nums[i] >= 1000 && nums[i] < 10000))
count ++;
}
return count;
}
```

# Perfect number

```bool checkPerfectNumber(int num)
{
if( num == 0 || (num == 1))
return false;
int i, sum = 1, sq = sqrt(num);
for (i = 2; i < sq; ++i)
if (num % i == 0)
sum += i + num / i;
if (num % sq == 0)
sum += (num / sq == sq) ? sq : sq + num / sq;
return sum == num;
}
```

# Complete square

```//The complete square can be found by accumulating odd numbers from 1,
//
//1 = 1;
//4 = 1 + 3;
//9 = 1 + 3 + 5;
//16 = 1 + 3 + 5 + 7;
//...
bool isPerfectSquare(int num)
{
if (num == 0 )
return false;
int i = 1;
while ( num > 0){
num -= i;
i += 2;
}
return num == 0;
}
```

```#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

typedef int DataType;
typedef struct Node
{
DataType data;
struct Node *next;
}Node;

int Delete(Node *s,DataType *ptr)
{
Node *p = NULL,*q = NULL;
p = s;
while(p->next->next != s)
{
p = p->next;
}
q = p->next;
*ptr = q->data;
p->next = s;
free(q);
return 1;
}
```

# Same number

```/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     struct TreeNode *left;
*     struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct TreeNode* q)
{
if( p == NULL && q == NULL )
return ture;
else
{
if( p == NULL || q == NULL )
return false;
else
{
if( p->val == q->val )
return isSameTree( p->left, q->left)&&isSameTree( p->right, q->right);
else return false
}
}
}
```

# Rotate array

```void rotate(int* nums, int numsSize, int k)
{
int i = 0, j = 0, temp = 0;
k %= numsSize;				//The length of rotation is less than mssize
for (i = 0, j = numsSize - 1 - k; i<j; i++, j--)	//Reverse the first half
{
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
for (i = numsSize - k, j = numsSize - 1; i<j; i++, j--)	//Reverse the second half
{
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
for (i = 0, j = numsSize-1; i<j; i++, j--)	//Invert the entire array
{
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
```

# Coin arrangement

```int arrangeCoins(int n)
{
return (int)(Math.sqrt(2) * Math.sqrt(n+0.125)-0.5);
}
```

# Children with the most candy

/*Give you an array? candies? And an integer? extraCandies?， Among them? candies[i]? Represents the number of sweets owned by the ith child.

For each child, check whether there is a program that will be additional? extraCandies? After a candy is distributed to the children, which child has the most? Candy. Note that multiple children are allowed to have the most at the same time? The number of sweets.

?

Example 1:

Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Explanation:
Child 1 has 2 sweets. If he gets all the extra sweets (3), he has a total of 5 sweets, and he will become the child with the most sweets.
Child 2 has three sweets. If he gets at least two extra sweets, he will become the child with the most sweets.
Child 3 has five sweets. He has the most sweets.
Child 4 has one candy. Even if he gets all the extra candy, he has only four candy. He can't be the child with the most candy.
Child 5 has three sweets. If he gets at least two extra sweets, he will become the child with the most sweets.
Example 2:

Input: candies = [4,2,1,1,2], extraCandies = 1
Output: [true,false,false,false,false]
Explanation: there is only one extra candy, so no matter who gives the extra candy, only child 1 can become the child with the most candy.
Example 3:

Input: candies = [12,1,12], extraCandies = 10
Output: [true,false,true]
?

Tips:

2 <= candies.length <= 100
1 <= candies[i] <= 100
1 <= extraCandies <= 50

Source: LeetCode

```bool* kidsWithCandies(int* candies, int candiesSize, int extraCandies, int* returnSize)
{
int i;
int maximum = 0;
bool *output = (bool *)malloc(sizeof(bool) * candiesSize);

// Traverse the candy quantity of each child and find the maximum candy quantity
for(i=0;i<candiesSize;i++)
{
if(candies[i] > maximum) maximum = candies[i];
}

//  Give extra candies to only one child,
//  Find the child whose total candy quantity is greater than or equal to the maximum candy quantity at this time, mark true, and the rest mark false
for(i=0;i<candiesSize;i++)
{
if (candies[i] + extraCandies >= maximum)
output[i] = true;
else
output[i] = false;
}

*returnSize = candiesSize;
return output;
}
```

# Valid parentheses

```bool isValid(char * s)
{
if(*s == 0) return true; 	// Empty string match
int len = strlen(s);
if(len & 1) return false;	// Odd length string does not match
char stack[len];
int top = -1;
for(int i=0; i<len; i++)	// If it is an open bracket, put it on the stack
{
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
stack[++top] = s[i];
else 					// Not an open parenthesis
if(top == -1)
return false;
else if(s[i] == stack[top]+1 || s[i] == stack[top]+2)
//In the ASCII table, the difference between the left parenthesis and its corresponding parenthesized ASCII value is no more than 2
//() 40, 41; [] is 90, 93; {} is 123125
stack[top--] = 0;
else
return false;
}
return top == -1;// Finally, if the stack is empty, it conforms, and if it is not empty, it does not conform
}
```

# The difference between the sum of the products of integers

```int subtractProductAndSum(int n)
{
int add = 0， mul = 1;
while(n > 0)
{
int a = n % 10;
n /= 10;
mul *=a;
}
}
```

# grow flowers

```bool canPlaceFlowers(int* flowerbed, int flowerbedSize, int n)
{
int gap=1,i;
for( i = 0; i < flowerbedSize; i++)
{
if( flowerbed[i] == 0 )
gap++;
else
{
n = n - ( gap - 1 ) / 2;
gap = 0;
}
}
if( gap != 0 )
n = n - gap / 2;
return n<=0;
}
```

# Minimum number of k

```int* getLeastNumbers(int* arr, int arrSize, int k, int* returnSize)
{
int temp;
for(int i = 0; i < k;i++)
{
for(int j = i+1; j<arrSize;j++)
{
if(arr[i]>arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
int *a;
a = (int *)malloc(sizeof(int)*k);
for(int i = 0; i<k; i++)
{
a[i] = arr[i];
}
*returnSize = k;
return a;
}
```

# Shift string left

```/*C The string should have one more unit to store '\ 0', otherwise it will overflow*/
char* reverseLeftWords(char* s, int n)
{
if(s[0] == '\0' || n <= 0)
return s;
int i = strlen(s);
char *p = malloc(sizeof(char)*(i+1));
for(int j = 0; j < i - n; j++)
p[j] = s[n+j];
for(int k = 0; k < n; k++)
p[i - n + k] = s[k];
p[i] = '\0';
return p;
}
```

# summary

Here is a summary of the article: