Created
October 23, 2019 21:22
-
-
Save ulisseslima/26cc59a69d005de4b2f8207692a3c9b6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package it.murah.utils; | |
import java.util.ArrayList; | |
import java.util.List; | |
import it.murah.utils.ex.Range; | |
/** | |
* @since 04/07/2013 | |
* @author Ulisses Lima | |
*/ | |
public class NumberUtils { | |
/** | |
* e.g.: breakPow2(176) = [16, 32, 128] | |
* | |
* @param n number made by summing up different powers of 2 | |
* @return list of powers of two that make up n | |
* @author Ulisses Lima | |
*/ | |
public static List<Long> breakPow2(long n) { | |
List<Integer> remainders = new ArrayList<>(); | |
List<Long> pow2s = new ArrayList<>(); | |
while (n > 0) { | |
remainders.add((int) n % 2); | |
n = n / 2; | |
} | |
for (int i = 0; i < remainders.size(); i++) { | |
Integer remainder = remainders.get(i); | |
if (remainder == 1) { | |
pow2s.add((long) Math.pow(2, i)); | |
} | |
} | |
return pow2s; | |
} | |
public static void main(String[] args) { | |
System.out.println(NumberUtils.breakPow2(176)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment