문제 풀기/C#

101. 2개 이하로 다른 비교

kagan-draca 2025. 3. 25. 17:24

 

기본 틀 :

 

using System;

public class Solution {
    public long[] solution(long[] numbers) {
        long[] answer = new long[] {};
        return answer;
    }
}

 

위의 문제를 푼다고 애먹었다...

 

먼저 long[] numbers를 2진수로 변경할 필요가 존재한다.

 

그래서,

 

    public long[] solution(long[] numbers) 
    {
        string[] bit = new string[numbers.Length];
        
        for(int i = 0; i < bit.Length; i++)
        {
            bit[i] = Convert.ToString(numbers[i], 2);
            string temp = "0" + bit[i];

 

위와 같은 코드로 2진수로 변경 및 앞에 "0"을 추가해 "01"이 "10"이 될 상황을 고려해줬다.

 

그 다음으로는 다음 비트를 구해주면 되는데 2진수의 1의 자리 수가 0이면 

 

1로 바꿔 다음 숫자로 비트를 변경해줬다.

            if(temp[temp.Length - 1] == '0') temp = temp.Substring(0, temp.Length - 1) + '1';

 

반대로, 2진수의 1의 자리 수가 1이면

 

문자열에서 "01"이 뒤에서 처음 나오는 지점을 10으로 변경해줘야 하기 때문에

 

            else
            {
                int index = temp.LastIndexOf("01");
                //Substring 매개변수 입력 순서
                // 시작 index
                // 자를 개수(count)(입력 안 할 경우 index ~ 끝 까지)
                temp = temp.Substring(0, index) + "10" + temp.Substring(index + 2);
            }

 

위와 같이 코드를 작성해줬다.

 

그렇게 변경된 2진수 문자열을 다시 10진수로 변경하기 위해

 

Convert.ToInt를 사용하면 되는데 ToInt32를 할 경우 

 

0 <= numbers의 모든 수 <= 10^15

 

조건에 의해 10^15범위를 나타내지 못 하기 때문에

 

ToInt64를 사용해야 했다.

 

using System;
using System.Collections.Generic;

public class Solution {
    public long[] solution(long[] numbers) 
    {
        string[] bit = new string[numbers.Length];
        
        for(int i = 0; i < bit.Length; i++)
        {
            bit[i] = Convert.ToString(numbers[i], 2);
            string temp = "0" + bit[i];
            
            if(temp[temp.Length - 1] == '0') temp = temp.Substring(0, temp.Length - 1) + '1';
            else
            {
                int index = temp.LastIndexOf("01");
                //Substring 매개변수 입력 순서
                // 시작 index
                // 자를 개수(count)(입력 안 할 경우 index ~ 끝 까지)
                temp = temp.Substring(0, index) + "10" + temp.Substring(index + 2);
            }
            
            numbers[i] = Convert.ToInt64(temp, 2);
        }
        
        return numbers;
    }
}