All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g1001_1100.s1017_convert_to_base_2.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g1001_1100.s1017_convert_to_base_2;

// #Medium #Math #2022_05_02_Time_1_ms_(89.45%)_Space_39.8_MB_(84.40%)

/**
 * 1017 - Convert to Base -2\.
 *
 * Medium
 *
 * 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
**/
public class Solution {
    public String baseNeg2(int n) {
        StringBuilder sb = new StringBuilder(Integer.toBinaryString(n));
        sb.reverse();
        int carry = 0;
        int sum;
        int pos = 0;
        while (pos < sb.length()) {
            sum = carry + sb.charAt(pos) - '0';
            sb.setCharAt(pos, sum % 2 == 0 ? '0' : '1');
            carry = sum / 2;
            if (pos % 2 == 1 && sb.charAt(pos) == '1') {
                carry += 1;
            }
            pos++;
            if (pos >= sb.length() && carry > 0) {
                sb.append(Integer.toBinaryString(carry));
                carry = 0;
            }
        }
        return sb.reverse().toString();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy