按位运算符,左移和右移如何工作
BItwise Operator, how does Left shift and right shift works
public class Solution {
public int GetSum(int a, int b) {
while(b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
}
所以问题是在不使用算术运算符的情况下将两个数字相加,我在 leetcode 讨论部分找到了解决方案,但我不确定进位变量是如何工作的
public class Solution {
public int GetSum(int a, int b) {
// Iterate till there is no carry
while(b != 0) {
// carry now contains common
// set bits of a and b
int carry = a & b;
// Sum of bits of a and
// b where at least one
// of the bits is not set
a = a ^ b;
// Carry is shifted by
// one so that adding it
// to a gives the required sum
b = carry << 1;
}
return a;
}
}
example
当你像这样调用求和函数时
GetSum(60, 13)
/* 60 = 0011 1100 */
/* 13 = 0000 1101 */
while(b != 0)
(它的while循环,它会循环直到b变为0)
int carry = a & b;; // a=60 & 13
会变成12
/* 12 = 0000 1100 */
a = a ^ b;
会变成49
/* 49 = 0011 0001 */
b = carry << 1;
会因为Binary Left Shift Operator(<<)
变成24
。左操作数值向左移动 right operand
指定的位数,它将循环并计算 continue
就像我解释的那样
public class Solution {
public int GetSum(int a, int b) {
while(b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
}
所以问题是在不使用算术运算符的情况下将两个数字相加,我在 leetcode 讨论部分找到了解决方案,但我不确定进位变量是如何工作的
public class Solution {
public int GetSum(int a, int b) {
// Iterate till there is no carry
while(b != 0) {
// carry now contains common
// set bits of a and b
int carry = a & b;
// Sum of bits of a and
// b where at least one
// of the bits is not set
a = a ^ b;
// Carry is shifted by
// one so that adding it
// to a gives the required sum
b = carry << 1;
}
return a;
}
}
example
当你像这样调用求和函数时
GetSum(60, 13)
/* 60 = 0011 1100 */
/* 13 = 0000 1101 */
while(b != 0)
(它的while循环,它会循环直到b变为0)
int carry = a & b;; // a=60 & 13
会变成12
/* 12 = 0000 1100 */
a = a ^ b;
会变成49
/* 49 = 0011 0001 */
b = carry << 1;
会因为Binary Left Shift Operator(<<)
变成24
。左操作数值向左移动 right operand
指定的位数,它将循环并计算 continue
就像我解释的那样