
给定一个数字 n,我们必须使用异或运算来打印将数字制成 2^X-1 形式的步骤。
我们应该进行异或任意 2^M-1 的数字,其中 M 由您选择,在奇数步长。 在偶数步长,将数字增加 1
继续执行该步骤,直到n变为2^X-1,并打印所有步骤
示例
Input: 22Output: Step 1 : Xor with 15 Step 2: Increase by 1 Step 3 : Xor with 7 Step 4: Increase by 1 Step 5 : Xor with 1Input:7Output: No Steps to be performed
算法
int find_leftmost_unsetbit(int n)STARTSTEP 1 : DECLARE AND ASSIGN ind = -1, i = 1STEP 2 : LOOP WHILE n IF !(n & 1) THEN, ASSIGN ind WITH i END IF INCREMENT i BY 1 LEFT SHIFT n BY 1END WHILeSTEP 3 : RETURN indSTOPvoid perform_steps(int n)STARTSTEP 1 : DECLARE AND ASSIGN left = find_leftmost_unsetbit(n)STEP 2 : IF left == -1 THEN, PRINT "No Steps to be performed" RETURNEND IFSTEP 3 : DECLARE AND ASSIGN step = 1STEP 4 : LOOP WHILE find_leftmost_unsetbit(n) != -1 IF step % 2 == 0 THEN, INCREMENT n BY 1 PRINT "Step n : Increase by 1" ELSE DECLARE AND ASSIGN m = find_leftmost_unsetbit(n) AND SET num = (pow(2, m) - 1) SET n = n ^ num PRINT "Step N : Xor with Num END IF INCREMENT step BY 1END LOOPSTOP
示例
#include #include
输出
如果我们运行上面的程序,那么它将生成以下输出 –
Step 1 : Xor with 15Step 2 : Increase by 1Step 3 : Xor with 7Step 4 : Increase by 1Step 5 : Xor with 1
以上就是打印在C程序中生成形如2^X – 1的数字的步骤的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444597.html
微信扫一扫
支付宝扫一扫