leetcode

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

commit 4ce00a1a73a5f6cefa4a9e831bee501fd945591a
parent d3ea88cbdf36833f773e26694de6a1c71d501e47
Author: Jack Sangdahl <jack@pngu.org>
Date:   Sat,  8 Nov 2025 19:05:13 -0700

2169. count operations to obtain zero

Diffstat:
Acount_ops_obtain_zero.c | 37+++++++++++++++++++++++++++++++++++++
Acount_ops_obtain_zero.py | 26++++++++++++++++++++++++++
2 files changed, 63 insertions(+), 0 deletions(-)

diff --git a/count_ops_obtain_zero.c b/count_ops_obtain_zero.c @@ -0,0 +1,37 @@ +// 2169. Count Operations to Obtain Zero +#include "leetcode.h" + +/* + * you are given two non-negative integers 'num1' and 'num2'. in one operation, + * if 'num1 >= num2', you must subtract 'num2' from 'num1' otherwise subtract + * 'num1' from 'num2'. return the number of operations required to make either + * 'num1 = 0', or 'num2 = 0' + */ + +static inline __attribute__((always_inline)) int32_t iif(int32_t a, int32_t b, + int c) { + return (a & (-c)) + (b & (~(-c))); +} + +static inline __attribute__((always_inline)) void swap(int32_t *a, int32_t *b) { + int32_t cond = iif(~(int32_t)0, 0, *a > *b); + int32_t mask = (*a ^ *b) & cond; + *a ^= mask; + *b ^= mask; +} + +int countOperations(int num1, int num2) { + int cnt = 0; + while (num1 && num2) { + swap(&num2, &num1); + int tmp = num1 / num2; + cnt += tmp; + num1 -= tmp * num2; + } + return cnt; +} + +int main() { + printf("%d\n", countOperations(2, 3)); // expect: 3 + printf("%d\n", countOperations(10, 10)); // expect: 1 +} diff --git a/count_ops_obtain_zero.py b/count_ops_obtain_zero.py @@ -0,0 +1,26 @@ +# 2169. Count Operations to Obtain Zero + +""" +you are given two non-negative integers 'num1' and 'num2'. in one operation, +if 'num1 >= num2', you must subtract 'num2' from 'num1' otherwise subtract +'num1' from 'num2'. return the number of operations required to make either +'num1 = 0', or 'num2 = 0' +""" + + +class Solution(object): + def countOperations(self, num1, num2): + """ + :type num1: int + :type num2: int + :rtype: int + """ + return ( + 0 if num2 == 0 else num1 // num2 + self.countOperations(num2, num1 % num2) + ) + + +if __name__ == "__main__": + obj = Solution() + print(obj.countOperations(num1=2, num2=3)) + print(obj.countOperations(num1=10, num2=10))