###### tags: `LeetCode` `C` `Two Sum` # LeetCode 1 Two Sum === ```clike= int* twoSum(int* nums, int numsSize, int target, int* returnSize){ int i, j; int *ptr; *returnSize=2; for(i=0;i<numsSize;i++){ for (j=i;j<numsSize-1;j++){ if (nums[i]+nums[j+1]==target){ ptr=(int*)malloc(2*sizeof(int)); *(ptr)=i; *(ptr+1)=j+1; } } } return ptr; // return NULL; } ``` 來源: [Leetcode 1. Two Sum](https://leetcode.com/problems/two-sum/) 21 Merge Two Sorted Lists === ```clike= struct ListNode mergeTwoLists(struct ListNode l1, struct ListNode* l2){ struct ListNode* newnode=(struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode* new=newnode; if(l1==NULL)return l2; if(l2==NULL)return l1; while(l1!=NULL && l2!=NULL) { if(l1->val <= l2->val) { new->next=l1; l1=l1->next; } else { new->next=l2; l2=l2->next; } new=new->next; } if(l1==NULL) new->next=l2; else if(l2==NULL)new->next=l1; return newnode->next;} ``` 206 Reverse Linked List === ```clike= struct ListNode* reverseList(struct ListNode* head){ struct ListNode *cur=head, *pre=NULL, *next; while(cur!=NULL){ next=cur->next; cur->next=pre; pre=cur; cur=next; } return pre; } ``` 來源: [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) 136 Single Number === ```clike= int singleNumber(int* nums, int numsSize){ int result = 0; for (int i = 0; i<numsSize; i++) { result ^=nums[i]; } return result; } ``` 來源: [136. Single Number](https://leetcode.com/problems/single-number/) 190 Reverse Bits === ```clike= uint32_t reverseBits(uint32_t n) { uint32_t b={0}; for(int i=0;i<32;i++){ b<<=1; b+=n&1; n>>=1; } return b; } ``` 來源: [190. Reverse Bits](https://leetcode.com/problems/reverse-bits/) 191 Number of 1 Bits === ```clike= int hammingWeight(uint32_t n) { int count=0; while(n!=0){ if(n&1) count++; n>>=1; } return count; } ``` 來源: [191. Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) 344 Reverse String === ```clike= void reverseString(char* s, int sSize){ int i; char temp; for(int i=0;i<=(sSize-1)/2;i++){ temp=s[i]; s[i]=s[sSize-1-i]; s[sSize-1-i]=temp; } return s; } ``` 來源: [344. Reverse String](https://leetcode.com/problems/reverse-string/) 617 Merge Two Binary Trees === ```clike= struct TreeNode* mergeTrees(struct TreeNode* root1, struct TreeNode* root2){ if (root1 == NULL) return root2; else if (root2 == NULL) return root1; root1->val += root2->val; root1->left = mergeTrees(root1->left, root2->left); root1->right = mergeTrees(root1->right, root2->right); return root1; } ``` 來源: [617. Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/) 1486 XOR Operation in an Array === ```clike= int xorOperation(int n, int start){ int result=0; int nums[n]; for (int i=0;i<n;i++){ nums[i] =start + 2*i; result^=nums[i]; } return result; } ``` 來源: [1486. XOR Operation in an Array](https://leetcode.com/problems/xor-operation-in-an-array/)