[11966] 2의 제곱인가?

RudinP·2023년 4월 20일
0

BaekJoon

목록 보기
53/77

생각

2의 제곱수는 비트로 표현 시 1이 한개만 있어야 한다.
즉, n과 2^30을 & 했을때 1이 1개면 된다.

처음 코드

namespace SongE
{
    public class Program
    {
        static int BinaryCounter(uint num, int count)
        {
            uint halfNum = num >> 1;
            bool isOne;
            if (num == 0) return count;

            isOne = (num != (halfNum + halfNum));
            if (isOne) count++;
            count = BinaryCounter(halfNum, count);
            return count;
        }

        static void Main(string[] args)
        {   
            using var input = new System.IO.StreamReader(Console.OpenStandardInput());
            using var print = new System.IO.StreamWriter(Console.OpenStandardOutput());

            int intInput() => int.Parse(input.ReadLine());
            //int[] intsInput() => Array.ConvertAll(input.ReadLine().Split(), s => int.Parse(s));
            
            uint n = (uint)intInput();
            uint a = n & 0b_11_1111_1111_1111_1111_1111_1111_1111;

            print.WriteLine(BinaryCounter(a, 0) == 1 ? 1 : 0);

        }
    }
}

틀렸는데
2^30이면 31자리 있어야하는걸 까먹음 ㅋㅋ

두번째 코드

namespace SongE
{
    public class Program
    {
        static int BinaryCounter(uint num, int count)
        {
            uint halfNum = num >> 1;
            bool isOne;
            if (num == 0) return count;

            isOne = (num != (halfNum + halfNum));
            if (isOne) count++;
            count = BinaryCounter(halfNum, count);
            return count;
        }

        static void Main(string[] args)
        {   
            using var input = new System.IO.StreamReader(Console.OpenStandardInput());
            using var print = new System.IO.StreamWriter(Console.OpenStandardOutput());

            int intInput() => int.Parse(input.ReadLine());
            //int[] intsInput() => Array.ConvertAll(input.ReadLine().Split(), s => int.Parse(s));
            
            uint n = (uint)intInput();
            uint a = n & 0b_111_1111_1111_1111_1111_1111_1111_1111;

            print.WriteLine(BinaryCounter(a, 0) == 1 ? 1 : 0);

        }
    }
}

profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글