To binary
A non-negative integer n is given.
Print n in binary, with no leading zeros.
If n is 0, print 0.
- Input
- 0 ≤ n ≤ 10^9
- Output
- n in binary on one line
13
1101
0
0
A non-negative integer n is given.
Print n in binary, with no leading zeros.
If n is 0, print 0.
13
1101
0
0
When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).
$ Ready
Open this on a computer to write and run code. On mobile you can read the problem and the solutions.
Remainders mod 2 come out lowest digit first, so prepend them or reverse at the end.
The common trap is a plain while (n > 0): for n = 0 the loop never runs and you print an empty line.
A do … while that runs the body once first (Java, C#, C, C++, JavaScript, TypeScript) fits exactly; Python and Craykon have no do, so they handle 0 separately.
Built-ins: Python bin(n)[2:], JavaScript n.toString(2), Java Integer.toBinaryString(n), C# Convert.ToString(n, 2), all of which give "0" for 0.
In Craykon it is while (n > 0) { … n = Mathf.Quot(n, 2); }; / divides into decimals, so use the quotient.
n = int(input())if n == 0: print(0)else: digits = "" while n > 0: digits = str(n % 2) + digits n //= 2 print(digits)let n = Number(require("fs").readFileSync(0, "utf8").trim());let digits = "";do { digits = (n % 2) + digits; n = Math.floor(n / 2);} while (n > 0);console.log(digits);import { readFileSync } from "node:fs";let n: number = Number(readFileSync(0, "utf8").trim());let digits = "";do { digits = (n % 2) + digits; n = Math.floor(n / 2);} while (n > 0);console.log(digits);import java.util.Scanner; public class Main { public static void main(String[] args) { int n = new Scanner(System.in).nextInt(); StringBuilder digits = new StringBuilder(); do { digits.append(n % 2); n /= 2; } while (n > 0); System.out.println(digits.reverse()); }}using System;using System.Text; class Program{ static void Main() { int n = int.Parse(Console.ReadLine().Trim()); var digits = new StringBuilder(); do { digits.Insert(0, n % 2); n /= 2; } while (n > 0); Console.WriteLine(digits); }}#include <algorithm>#include <iostream>#include <string> int main() { int n; std::cin >> n; std::string digits; do { digits += char('0' + n % 2); n /= 2; } while (n > 0); std::reverse(digits.begin(), digits.end()); std::cout << digits << '\n';}#include <stdio.h> int main(void) { int n; scanf("%d", &n); char digits[32]; int len = 0; do { digits[len++] = '0' + n % 2; n /= 2; } while (n > 0); for (int i = len - 1; i >= 0; i--) putchar(digits[i]); putchar('\n'); return 0;}n = Console.ReadLine().ToNumber();if (n == 0){ Console.WriteLine("0");}else{ digits = ""; while (n > 0) { digits = n % 2 + digits; n = Mathf.Quot(n, 2); } Console.WriteLine(digits);}