Machineboy空
비트연산자 활용법 <<, >>, Math.Pow 본문
비트연산 활용
idx번째 비트 끄기 | S &= -(1<< idx) |
idx번째 비트 XOR 연산 | S ^= (1 << idx) |
최하위 켜져있는 비트 찾기 | idx = (S & -S) |
크기가 n인 집합의 모든 비트를 켜기 | (1 << n) -1 |
idx번째 비트를 켜기 | S |= (1 << idx) |
idx번째 비트가 켜져있는지 확인하기 | if(S & (1 << idx)) |
idx 번째 비트 끄기
S &= ~ (1 << idx)
int S = 18;
int idx = 1;
S &= ~(1 << idx);
cout << S << '\n';
// 결과값 16 , 10000(2)

idx 번째 비트 XOR연산
S ^= (1 << idx)
토글 기능이랑 비슷, 스위치 켜고 끄기처럼 원하는 idx 비트 껐다 켰다 하는 법

최하위 켜져있는 비트 찾기
idx = (S & -S)

크기가 n인 집합의 모든 비트 켜기
(1 << n) -1

idx번째 비트를 켜기
S |= (1 << idx)

idx번째 비트가 켜져있는지 확인하기
if(S & (1 << idx))

https://exercism.org/tracks/csharp/exercises/allergies
Allergies in C# on Exercism
Can you solve Allergies in C#? Improve your C# skills with support from our world-class team of mentors.
exercism.org
using System;
using System.Collections.Generic;
public enum Allergen
{
Eggs ,
Peanuts ,
Shellfish ,
Strawberries ,
Tomatoes ,
Chocolate ,
Pollen ,
Cats
}
public class Allergies
{
bool[] binary = new bool[8];
public Allergies(int mask)
{
// mask를 이진수로 바꿔서 binary에 저장
for(int i = 0; i < 8; i++){
if((mask & (1 << i)) != 0){
binary[i] = true;
}
}
}
public bool IsAllergicTo(Allergen allergen)
{
// 앞에서 부터 탐색? 하며 켜져있으면 true 반환
return binary[(int)allergen];
}
public Allergen[] List()
{
List<Allergen> list = new List<Allergen>();
for(int i = 0; i < 8; i++)
{
if(binary[i])
{
list.Add((Allergen)i);
}
}
return list.ToArray();
}
}
제곱의 합과 제곱
Math.Pow 활용
//2의 5승
return Math.Pow(2, 5);
//2의 5승까지의 합
return Enumerable.Range(1,64).Sum(Square);
<< shift 연산자 활용
//2의 5승
return 1 << 5;
//2의 5승까지의 합 (1 + 2*2 + 2*2*2 + 2*2*2*2 + 2*2*2*2*2)
return (1 << 6) - 1;
https://exercism.org/tracks/csharp/exercises/grains/dig_deeper
Dig Deeper into Grains in C# on Exercism
Explore different approaches and videos on how to solve Grains in C#.
exercism.org
'Computer > 알고리즘' 카테고리의 다른 글
애드혹(ad-hoc) 알고리즘 (0) | 2024.07.02 |
---|---|
모듈러 연산과 유클리드 호제법 (0) | 2024.06.17 |
완전탐색(브루트포스), 백트래킹(back tracking) - 조합 재귀함수 구현코드, 원상복구 (0) | 2024.02.21 |
트리 순회 (Tree traversal) - 후위 순회, 전위 순회, 중위 순회 (0) | 2024.02.08 |
깊이우선탐색(DFS) vs 너비우선탐색(BFS) (1) | 2024.02.08 |