1017. Convert to Base -2

Given a number N, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two).

The returned string must have no leading zeroes, unless the string is "0".

 

Example 1:

Input: 2
Output: "110"
Explantion: (-2) ^ 2 + (-2) ^ 1 = 2

Example 2:

Input: 3
Output: "111"
Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3

Example 3:

Input: 4
Output: "100"
Explantion: (-2) ^ 2 = 4

 

Note:

  1. 0 <= N <= 10^9

 

Approach #1: Math. [Java]

class Solution {
    public String baseNeg2(int N) {
        if (N == 0) return "0";
        StringBuilder sb = new StringBuilder();
        while (N != 0) {
            int remainder = N % (-2);
            N /= -2;
            if (remainder < 0) {
                remainder += 2;
                N += 1;
            }
            sb.append(remainder);
        }
        return sb.reverse().toString();
    }
}

  

<pre><code class="html">

#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<set>

using namespace std;

int main() {
    string str;
    cin >> str;
    map<char, int> mp;
    for (int i = 0; i < str.length(); ++i) {
        mp[str[i]]++;
    }
    int start = 0, cur = 0, end;
    vector<int> ans;
    for (int i = 0; i < str.length(); ++i) {
        if (mp[str[cur]] == 0) {
            bool flag = false;
            for (int j = 1; j < i; ++j) {
                if (mp[str[j]] != 0) {
                    cur = j;
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                ans.push_back(i-start);
                start = i;
                cur = start;
            }
        }
        mp[str[i]]--;
    }
    ans.push_back(str.length()-start);
    if (!ans.empty()) {
        cout << ans[0];
    }
    for (int i = 1; i < ans.size(); ++i)
        cout << " " << ans[i];

    return 0;
}

</code></pre>

 

Reference:

https://en.wikipedia.org/wiki/Negative_base#Calculation

https://www.geeksforgeeks.org/convert-number-negative-base-representation/

 

posted @ 2019-05-29 16:31  Veritas_des_Liberty  阅读(326)  评论(0编辑  收藏  举报