문제 : Lonely Integer
사용언어 : C#
문제 내용
Given an array of integers, where all elements but one occur twice, find the unique element.
Example
a = [1,2,3,4,3,2,1]
The unique element is 4.
Function Description
Complete the lonelyinteger function in the editor below.
lonelyinteger has the following parameter(s):
- int a[n]: an array of integers
Returns
- int: the element that occurs only once
Input Format
The first line contains a single integer, n, the number of integers in the array.
The second line contains n space-separated integers that describe the values in a.
Constraints
- 1 <= n < 100
- It is guaranteed that n is an odd number and that there is one unique element.
- 0 <= a[i] <= 100, where 0 <= i < n.
내 풀이
비트 연산자 XOR을 이용했다.
XOR 연산은 대응되는 비트가 같으면 0, 서로 다르면 1을 반환한다.
public static int lonelyinteger(List<int> a)
{
int result = 0;
foreach(var i in a)
{
result = result^i;
}
return result;
}
result 변수를 하나 만들고,
for문으로 list a의 멤버를 하나씩 돌면서
XOR연산을 한다.
비트 연산으로 같으면 0을 반환하기 때문에
쌍으로 있던 숫자들은 0이되고, 혼자 있던 숫자가 남게 된다.
비트 연산자(bitwise operator)
비트 연산자는 논리 연산자와 비슷하지만, 비트(bit) 단위로 논리 연산을 할 때 사용하는 연산자입니다.
또한, 비트 단위로 왼쪽이나 오른쪽으로 전체 비트를 이동하거나, 1의 보수를 만들 때도 사용됩니다.
비트 연산자설명
& | 대응되는 비트가 모두 1이면 1을 반환함. (비트 AND 연산) |
| | 대응되는 비트 중에서 하나라도 1이면 1을 반환함. (비트 OR 연산) |
^ | 대응되는 비트가 서로 다르면 1을 반환함. (비트 XOR 연산) |
~ | 비트를 1이면 0으로, 0이면 1로 반전시킴. (비트 NOT 연산, 1의 보수) |
<< | 지정한 수만큼 비트들을 전부 왼쪽으로 이동시킴. (left shift 연산) |
>> | 부호를 유지하면서 지정한 수만큼 비트를 전부 오른쪽으로 이동시킴. (right shift 연산) |
참고
http://www.tcpschool.com/cpp/cpp_operator_bitwise
코딩교육 티씨피스쿨
4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등
tcpschool.com