zoukankan      html  css  js  c++  java
  • 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/

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    基于Lucene/XML的站内全文检索解决方案
    内容管理系统(CMS)的设计和选型
    Lucene入门与使用[转]
    为自己的系统搞个全文搜索 参考值:2 (转)
    C# 时间函数
    Lucene倒排索引原理(转)
    什么是内容管理系统CMS?
    网络测试常用命令
    C#与C的区别
    人生致命的八个经典问题
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10944610.html
Copyright © 2011-2022 走看看