[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

解题思路

与转二进制类似

实现代码

// 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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,234评论 0 13
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,205评论 0 10
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 6,261评论 0 2
  • <center>#1 Two Sum</center> link Description:Given an arr...
    铛铛铛clark阅读 6,696评论 0 3
  • 侯召明 雪花儿飘飘,像个少女姗姗来迟,过完元旦,人们就盼望着下雪。雪下多了,下早了,都不会让人期盼。没有雪...
    春明子阅读 3,332评论 0 1

友情链接更多精彩内容