[PS] LeetCode-1486
Problem Solving: 1486-XOR Operation in an Array
Introduction
Notes during problem solving.
Motivation
After taking Operating Systems, I realized I needed more practice using C.
Usually, I don’t like to do repetitive tasks, but desperate times call for desperate measures.
Preperation
Decided on the topics I will focus on solving first.
- Bit manipulation
- File I/O
- Pointers
Problem Description
You are given an integer n
and an integer start
.
Define an array nums
where nums[i] = start + 2 * i
(0-indexed) and n == nums.length.
Return the bitwise XOR of all elements of nums
.
Code
int xorOperation(int n, int start);
void increment_nums(int *nums, int n, int offset);
int xor_num(int *nums, int n);
int
xorOperation (int n, int start)
{
int *nums;
nums = (int *) malloc(sizeof(int) * n);
increment_nums(nums, n, start);
int xor_result = xor_nums(nums, n);
free(nums);
return xor_result;
}
void
increment_nums (int *nums, int n, int offset)
{
for (int i = 0; i < n; i++) {
nums[i] = offset + (2 * i);
}
}
int
xor_nums (int *nums, int n)
{
int accumulate_xor = 0;
for (int i = 0; i < n; i++) {
accumulate_xor = accumulate_xor ^ nums[i];
}
return accumulate_xor;
}
Solution Explanation
After allocating memory for the int array, it first increments the array by the given equation.
- This equation first gives an offset, start, then increments the consecutive values by 2.
- This makes the values constantly even or odd.
Then calling the xor_nums()
function, it simply accumulates the XOR’d values.
Code Explanation
- Syntax
Followed the GNU Coding Standards. - Functions
xorOperation()
: it was the default/fixed name given from LeetCode. I would have changed it toxor_operations()
to match snake case.increment_nums()
: separated the incrementing process from the driver function. Along withxor_nums()
, I named the function with the syntax, operation_arrayname.xor_nums()
: iteratively apply XOR operations. Return the accumulated value.
- Variables
xor_result
: holds the entire XOR operation in the array result.offset
: initiallystart
, but changed tooffset
in the function. As the operation is more like an offset.accumulate_xor
: variable that accumulates the calculated XOR operation values.
- Etc.
- other values were pre-defined, and used for consistency.
Conclusion
I’m really thrilled to continue this series.
Throughout this semester(23-1), I learned how to keep consistency and grit.
Most importantly, I earned confidence in my grit. Whether the field is coding, exercising, or etc.
Just like my [Study] logs, recording my thoughts instead of just the facts seems better.
I think this is because it helps me organize what I’ve learned throughout the years.
- I’m planning on writing a log about this.
Thanks for reading.