알고리즘/codewars

codewars: Base -2

꾸준함. 2018. 2. 7. 02:27

문제 링크입니다: https://www.codewars.com/kata/base-2

그동안 2진수, 8진수, 16진수는 많이 접해봤지만 음수진수들은 처음 접하는 것 같습니다.

나름 흥미로운 문제였습니다.

Base -2

/*

음수이진법을 구현하시오

*/

#include <iostream>

#include <string>

using namespace std;

 

class Negabinary {

public:

        static std::string ToNegabinary(int i);

        static int ToInt(std::string s);

};

 

int pow(int num)

{

        if (num == 0)

               return 1;

        else if (num == 1)

               return -2;

        if (num % 2==1)

               return pow(num - 1) * (-2);

        int half = pow(num / 2);

        return half * half;

}

 

std::string Negabinary::ToNegabinary(int i)

{

        std::string result;

        if (i == 0)

               return "0";

        //이진법 구하는 것과 똑같이 하면 된다

        while (abs(i) > 0) //절대값이 0이 아닐때까지

        {

               int remainder = i%(-2);

               i /= (-2);

 

               if (remainder < 0) //중요! 나머지가 음수일 경우 숫자를 1 더해줘야한다

               {

                       remainder += 2;

                       i++;

               }

               result += to_string(remainder);

        }

        std::reverse(result.begin(), result.end()); //거꾸로 변경

        return result;

}

 

int Negabinary::ToInt(std::string s)

{

        int sum = 0, cnt = 0;

        for (int i = 0; i < s.size(); i++)

               if (s[i] - '0' == 1) //1일때만

                       sum += pow(s.size()-i-1);

        return sum;

}

 

int main(void)

{

        cout << Negabinary::ToNegabinary(6) << endl;

        cout << Negabinary::ToNegabinary(-6) << endl;

        cout << Negabinary::ToNegabinary(4587) << endl;

        cout << Negabinary::ToInt("11010") << endl;

        cout << Negabinary::ToInt("1110") << endl;

        cout<<Negabinary::ToInt("1011000111111")<<endl;

        return 0;

}


개발환경:Visual Studio 2017


지적, 조언, 질문 환영입니다! 댓글 남겨주세요~

반응형

'알고리즘 > codewars' 카테고리의 다른 글

codewars: Some Egyptian fractions  (0) 2018.02.14
codewars: Valid Braces  (0) 2018.02.14
codewars: RGB To Hex Conversion  (0) 2018.02.07
codewars: Fun with trees: is perfect  (0) 2018.02.06
codewars Validate Credit Card Number  (0) 2018.02.01