[LeetCode] 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:

0 <= N <= 10^9

解題思路

與轉(zhuǎn)二進制類似

實現(xiàn)代碼

// Runtime: 1 ms, faster than 97.49% of Java online submissions for Convert to Base -2.
// Memory Usage: 36.9 MB, less than 100.00% of Java online submissions for Convert to Base -2.
class Solution {
    public String baseNeg2(int N) {
        String res = "";
        while (N != 0) {
            //res = Integer.toString(N & 1) + res;
            res = (N & 1) + res;
            N = - (N >> 1);
        }
        
        return res == "" ? "0" : res;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,894評論 0 13
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,817評論 0 10
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些閱讀 2,132評論 0 2
  • <center>#1 Two Sum</center> link Description:Given an arr...
    鐺鐺鐺clark閱讀 2,345評論 0 3
  • 侯召明 雪花兒飄飄,像個少女姍姍來遲,過完元旦,人們就盼望著下雪。雪下多了,下早了,都不會讓人期盼。沒有雪...
    春明子閱讀 512評論 0 1

友情鏈接更多精彩內(nèi)容