LeetCode 1017. Convert to Base -2

原题链接在这里:https://leetcode.com/problems/convert-to-base-2/description/

题目:

Given an integer n, return a binary string representing its representation in base -2.

Note that the returned string should not have leading zeros unless the string is "0".

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • 0 <= n <= 109

题解:

If it is to convert to base 2, we know append (n & 1) and then n >> 1.

For base -2, we just need to use n = -(n >> 1).

Here is the reason, 

n = (a3) * (-2)^3 + (a2) * (-2) ^ 2 + (a1) * (-2)^1+ (a0) * (-2)^0

n = (-a3)*2^3 + (a2)*2^2+ (-a1)*2^1 + (a0)*2^0

By n & 1, we get a0. by n >> 1, we move to (-a1), by n = -n, we get a1.

n= (-a3)*2^3+(a2)*2^2+(-a1)*2^1+(a0)*2^0 we get a0
-n= (a3)*2^2+ (-a2)*2^1+(a1)*2^0 we get a1
n= (-a3)*2^1+ (a2)*2^0 we get a2
-n= (a3)*2^0 we get a3

Time Complexity: O(logn).

Space: O(logn).

AC Java:

 1 class Solution {
 2     public String baseNeg2(int n) {
 3         if(n == 0){
 4             return "0";
 5         }
 6 
 7         StringBuilder sb = new StringBuilder();
 8         while(n != 0){
 9             sb.append(n & 1);
10             n = -(n >> 1);
11         }
12 
13         return sb.reverse().toString();
14     }
15 }

 

posted @ 2024-08-03 11:52  Dylan_Java_NYC  阅读(2)  评论(0编辑  收藏  举报