이 부울 "(number & 1) == 0"은 무엇을 의미합니까?
CodeReview 에서 작업 코드를 게시하고이를 개선하기위한 팁을 요청했습니다. 내가 얻은 하나는 부울 메서드를 사용하여 ArrayList에 짝수 개의 인덱스가 있는지 확인하는 것이 었습니다. 제안 된 코드는 다음과 같습니다.
private static boolean isEven(int number)
{
return (number & 1) == 0;
}
이미 많은 도움을 위해 특정 사용자를 괴롭 혔으므로 SO 커뮤니티를 괴롭힐 때라고 결정했습니다! 나는 이것이 어떻게 작동하는지 정말로 이해하지 못한다. 메서드가 호출되고 ArrayList의 크기를 매개 변수로 사용합니다 (즉, ArrayList에 10 개의 요소가 있음, 숫자 = 10).
나는 하나 &
가 숫자와 1의 비교를 실행한다는 것을 알고 있지만 그 후 길을 잃었습니다.
내가 읽는 방식은 if number == 0
and 1 == 0
. 나는 첫 번째는 사실이 아니며 후자는 분명히 말이되지 않는다는 것을 압니다. 아무도 나를 도울 수 있습니까?
편집 : 누군가 궁금해 할 경우 코드가 작동한다고 추가해야합니다.
"&"는 비트 연산입니다. 당신은 아마 이것을 알고있을 것입니다. 그러나 당신이 질문을 던진 방식에 근거하여 그것은 나에게 완전히 명확하지 않습니다.
즉, 이론적 인 아이디어는 일련의 1과 0으로 비트로 표현할 수있는 int가 있다는 것입니다. 예를 들면 :
...10110110
이진수에서는 2 진법이므로 숫자의 비트 버전이 0으로 끝날 때마다 짝수이고 1로 끝날 때 홀수입니다.
따라서 위의 경우 비트 및 1을 사용하여 수행하는 것은 다음과 같습니다.
...10110110 & ...00000001
물론 이것은 0이므로 원래 입력이 짝수라고 말할 수 있습니다.
또는 홀수를 고려하십시오. 예를 들어, 위에있는 것에 1을 더하십시오. 그때
...10110111 & ...00000001
1과 같으므로 0과 같지 않습니다. 짜잔.
이진 표현에서 마지막 비트 에 의해 숫자가 짝수인지 홀수인지 확인할 수 있습니다 .
1 -> 00000000000000000000000000000001 (odd)
2 -> 00000000000000000000000000000010 (even)
3 -> 00000000000000000000000000000011 (odd)
4 -> 00000000000000000000000000000100 (even)
5 -> 00000000000000000000000000000101 (odd)
6 -> 00000000000000000000000000000110 (even)
7 -> 00000000000000000000000000000111 (odd)
8 -> 00000000000000000000000000001000 (even)
&
두 정수 사이는 비트 AND 연산자입니다.
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
경우에 따라서, (number & 1) == 0
이다 true
,이 방법은 number
도이다.
다음을 가정 해 보겠습니다 number == 6
.
6 -> 00000000000000000000000000000110 (even)
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
1 -> 00000000000000000000000000000001
-------------------------------------
0 -> 00000000000000000000000000000000
그리고 언제 number == 7
:
7 -> 00000000000000000000000000000111 (odd)
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
1 -> 00000000000000000000000000000001
-------------------------------------
1 -> 00000000000000000000000000000001
&
비트 AND 연산자입니다. &&
논리 AND 연산자입니다.
이진수에서 숫자 비트가 설정되면 (즉, 1) 숫자는 홀수입니다.
2 진수에서 숫자 비트가 0이면 숫자는 짝수입니다.
(number & 1)
A는 비트가숫자 비트 AND 테스트입니다.
이를 수행하는 또 다른 방법 (효율성이 떨어지지 만 더 이해하기 쉬울 수 있음)은 모듈러스 연산자를 사용하는 것입니다 %
.
private static boolean isEven(int number)
{
if (number < 0)
throw new ArgumentOutOfRangeException();
return (number % 2) == 0;
}
This expression means "the integer represents an even number".
Here is the reason why: the binary representation of decimal 1
is 00000000001
. All odd numbers end in a 1
in binary (this is easy to verify: suppose the number's binary representation does not end in 1
; then it's composed of non-zero powers of two, which is always an even number). When you do a binary AND
with an odd number, the result is 1
; when you do a binary AND
with an even number, the result is 0
.
This used to be the preferred method of deciding odd/even back at the time when optimizers were poor to nonexistent, and %
operators required twenty times the number of cycles taken by an &
operator. These days, if you do number % 2 == 0
, the compiler is likely to generate code that executes as quickly as (number & 1) == 0
does.
Single &
means bit-wise and
operator not comparison
So this code checks if the first bit
(least significant/most right) is set or not, which indicates if the number is odd
or not; because all odd numbers will end with 1
in the least significant bit e.g. xxxxxxx1
&
is a bitwise AND
operation.
For number = 8:
1000
0001
& ----
0000
The result is that (8 & 1) == 0
. This is the case for all even numbers, since they are multiples of 2 and the first binary digit from the right is always 0. 1 has a binary value of 1 with leading 0s, so when we AND
it with an even number we're left with 0.
The &
operator in Java is the bitwise-and operator. Basically, (number & 1)
performs a bitwise-and between number
and 1
. The result is either 0 or 1, depending on whether it's even or odd. Then the result is compared with 0 to determine if it's even.
Here's a page describing bitwise operations.
It is performing a binary and against 1, which returns 0 if the least significant bit is not set
for your example
00001010 (10)
00000001 (1)
===========
00000000 (0)
This is Logical design concept bitwise & (AND)operater.
return ( 2 & 1 ); means- convert the value to bitwise numbers and comapre the (AND) feature and returns the value.
Prefer this link http://www.roseindia.net/java/master-java/java-bitwise-and.shtml
참고URL : https://stackoverflow.com/questions/14905643/what-does-this-boolean-number-1-0-mean
'Program Tip' 카테고리의 다른 글
토글 버튼 Android의 켜기 / 끄기 텍스트 변경 (0) | 2020.10.15 |
---|---|
grunt를 설치하는 방법 및 스크립트를 작성하는 방법 (0) | 2020.10.15 |
특정 열에 특정 문자열을 포함하는 Pandas 데이터 프레임에서 행을 삭제하는 방법은 무엇입니까? (0) | 2020.10.15 |
Xcode 7 오류 ITMS-90474 : "잘못된 번들", Apple에 제출할 수 없음 (0) | 2020.10.15 |
빈혈 도메인 모델 : 장점 / 단점 (0) | 2020.10.15 |