leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit bf3ec0f3cc855512baf637c6c2b914d60c40fc01
parent 6779cbd9ed0c98f31af5939304b5611a9efe5026
Author: Jack Sangdahl <jack@pngu.org>
Date:   Fri,  8 Nov 2024 19:58:33 -0700

3133. minimum array end

Diffstat:
Aminimum_array_end.c | 26++++++++++++++++++++++++++
Aminimum_array_end.py | 32++++++++++++++++++++++++++++++++
2 files changed, 58 insertions(+), 0 deletions(-)

diff --git a/minimum_array_end.c b/minimum_array_end.c @@ -0,0 +1,26 @@ +// 3133. Minimum Array End +#include "leetcode.h" + +/* + * you are given two integers 'n' and 'x'. you have to construct an array of + * positive integers 'nums'. of size 'n' where for every '0 <= i < n - 1', + * 'nums[i + 1]' is greater than 'nums[i]', and the result of the bitwise and + * operation between all elements of 'nums' is 'x'. return the minimum possible + * value of 'nums[n - 1]' + */ + +long long minEnd(int n, int x) { + n--; + long long a = x, b; + for (b = 1; n; b <<= 1) + if (!(b & x)) { + a |= (n & 1) * b; + n >>= 1; + } + return a; +} + +int main() { + printf("%lld\n", minEnd(3, 4)); // expect: 6 + printf("%lld\n", minEnd(2, 7)); // expect: 15 +} diff --git a/minimum_array_end.py b/minimum_array_end.py @@ -0,0 +1,32 @@ +# 3133. Minimum Array End + +""" +you are given two integers 'n' and 'x'. you have to construct an array of +positive integers 'nums'. of size 'n' where for every '0 <= i < n - 1', +'nums[i + 1]' is greater than 'nums[i]', and the result of the bitwise and +operation between all elements of 'nums' is 'x'. return the minimum possible +value of 'nums[n - 1]' +""" + + +class Solution(object): + def minEnd(self, n, x): + """ + :type n: int + :type x: int + :rtype: int + """ + n -= 1 + b = 1 + for i in range(64): + if b & x == 0: + x |= (n & 1) * b + n >>= 1 + b <<= 1 + return x + + +if __name__ == "__main__": + obj = Solution() + print(obj.minEnd(3, 4)) + print(obj.minEnd(2, 7))