Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Define maximum unsigned int
in binary as: 11 111 111 111 111 111 111 111 111 111 111
. For all input number XOR
with maximum and print the output.
Aware that some programming languages have signed numbers. It is better to use integer format bigger than 32-bit.
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Scanner; public class FlippingBits { private static int MAX = 0b11_111_111_111_111_111_111_111_111_111_111; public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); for(int i = 0; i < tests; i++) { int input = (int) Long.parseLong(stdin.nextLine()); System.out.println(Long.valueOf(Integer.toBinaryString(MAX ^ input), 2)); } stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function processData(input) { var numbers = input.split("\n").map(function(item) {return parseInt(item);}); for(var i = 1; i < numbers.length; i++ ) { console.log((~numbers[i]) >>> 0); } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Scala
1 2 3 4 5 6 7 8 9 |
import scala.io.Source object FlippingBits extends App { private[this] val MAX = java.lang.Long.parseLong("11111111111111111111111111111111", 2) val numbers = Source.stdin.getLines().drop(1).map(_.toLong) val flipped = numbers.map(_ ^ MAX) println(flipped.mkString("\n")) } |
Ruby
1 2 3 4 |
tests = gets.to_i tests.times do puts 0xffffffff ^ gets.to_i end |