## Tag Archives: binary

## C# || Counting Bits – How To Return The Number Of 1’s In Binary Representation Of X Using C#

The following is a module with functions which demonstrates how to return the number of 1’s in binary representation of X using C#.

1. Count Bits – Problem Statement

Given an integer **n**, return *an array ***ans*** of length ***n + 1*** such that for each ***i*** *(**0 <= i <= n**)*, ***ans[i]*** is the number of *

**1**

**‘s**in the binary representation of**i**.

**Example 1:**

Input:n = 2

Output:[0,1,1]

Explanation:

0 --> 0

1 --> 1

2 --> 10

**Example 2:**

Input:n = 5

Output:[0,1,1,2,1,2]

Explanation:

0 --> 0

1 --> 1

2 --> 10

3 --> 11

4 --> 100

5 --> 101

2. Count Bits – Solution

The following is a solution which demonstrates how return the number of 1’s in binary representation of X.

In this problem, we can see a pattern start to form.

When the current **n** is even, we can get the answer by dividing by 2 (e.g **result[n] = result[n / 2]**)

When the current **n** is odd, we can get the answer by getting the result at previous index and adding 1 (e.g **result[n] = result[n – 1] + 1**)

```
```
12345678910111213141516171819202122
// ============================================================================// Author: Kenneth Perkins// Date: Oct 2, 2022// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to return binary representation of X// ============================================================================public class Solution { public int[] CountBits(int n) { var result = new int[n + 1]; result[0] = 0; for (int index = 1; index < result.Length; ++index) { if (index % 2 == 0) { result[index] = result[index / 2]; } else { result[index] = result[index - 1] + 1; } } return result; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:

[0,1,1]

[0,1,1,2,1,2]

## C# || How To Add Two Binary Strings Using C#

The following is a module with functions which demonstrates how to add two binary strings together using C#.

1. Add Binary – Problem Statement

Given two binary strings **a** and **b**, return their sum as a binary string.

**Example 1:**

Input: a = "11", b = "1"

Output: "100"

**Example 2:**

Input: a = "1010", b = "1011"

Output: "10101"

2. Add Binary – Solution

The following is a solution which demonstrates how to add two binary strings together.

In this solution, we start at the end of both strings, and perform basic math on each number, adding them together. If any mathematical carry over is required, that is added to the next loop iteration.

```
```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
// ============================================================================// Author: Kenneth Perkins// Date: Oct 13, 2021// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to add two binary strings together// ============================================================================public class Solution { public string AddBinary(string a, string b) { // Process numbers starting from the end var aLength = a.Length - 1; var bLength = b.Length - 1; // Go through data and add each number together var stack = new Stack<int>(); var carry = 0; while (aLength >= 0 || bLength >= 0) { var aValue = 0; var bValue = 0; if (aLength >= 0) { aValue = CharToInt(a[aLength--]); } if (bLength >= 0) { bValue = CharToInt(b[bLength--]); } // Add the a and b values together, including carry var sum = carry + aValue + bValue; // Determine the carry over value carry = sum / 2; // Save the digit var digit = sum % 2; stack.Push(digit); } // Add any data left over if (carry > 0) { stack.Push(carry); } // Save results var result = new StringBuilder(); while (stack.Count > 0) { result.Append(stack.Peek()); stack.Pop(); } return result.ToString(); } private int CharToInt(char ch) { return ch - '0'; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:

"100"

"10101"

## C++ || Snippet – How To Convert A Decimal Number Into Binary

This page will demonstrate how to convert a decimal number (i.e a whole number) into its binary equivalent. So for example, if the decimal number of 26 was entered into the program, it would display the converted binary value of 11010.

**REQUIRED KNOWLEDGE FOR THIS SNIPPET**

`How To Count In Binary`

The "Long" Datatype - What Is It?

While Loops

Online Binary to Decimal Converter - Verify For Correct Results

How To Reverse A String

If you are looking for sample code which converts binary to decimal, check back here soon!

```
```
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
#include <iostream>#include <string>#include <algorithm> using namespace std; // function prototypestring DecToBin(long long decNum); int main(){ // declare variables long long decNum = 0; string binaryNum=""; // use a string instead of an int to avoid // overflow, because binary numbers can grow large quick cout<<"Please enter an integer value: "; cin >> decNum; if(decNum < 0) { binaryNum = "-"; } // call function to convert decimal to binary binaryNum += DecToBin(decNum); // display data to user cout<<"nThe integer value of "<<decNum<<" = "<<binaryNum<<" in binary"<<endl; return 0;} string DecToBin(long long decNum){ string binary = ""; // use this string to save the binary number if(decNum < 0) // if input is a neg number, make it positive { decNum *= -1; } // converts decimal to binary using division and modulus while(decNum > 0) { binary += (decNum % 2)+'0'; // convert int to char decNum /= 2; } // reverse the string reverse(binary.begin(), binary.end()); return binary;}// http://programmingnotes.org/

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

Note: The code was compiled 3 separate times to display different output

`====== RUN 1 ======`

Please enter an integer value: 1987

The integer value of 1987 = 11111000011 in binary

====== RUN 2 ======

Please enter an integer value: -26

The integer value of -26 = -11010 in binary

====== RUN 3 ======

Please enter an integer value: 12345678910

`The integer value of 12345678910 = 1011011111110111000001110000111110 in binary`

## Java || Snippet – How To Convert A Decimal Number Into Binary

This page will demonstrate how to convert a decimal number (i.e a whole number) into its binary equivalent. So for example, if the decimal number of 25 was entered into the program, it would display the converted binary value of 11001.

**REQUIRED KNOWLEDGE FOR THIS SNIPPET**

`How To Count In Binary`

The "Long" Datatype - What Is It?

Methods (A.K.A "Functions") - What Are They?

While Loops

Online Binary to Decimal Converter - Verify For Correct Results

If you are looking for sample code which converts binary to decimal, check back here soon!

```
```
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
import java.util.Scanner; public class DecimalToBinary{ // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables long decNum = 0; String binaryNum = ""; // use a string instead of an int to avoid // overflow, because binary numbers can grow large quick // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); // get decimal number from user System.out.print("Please enter an integer value: "); decNum = cin.nextLong(); if(decNum < 0) // if user inputs a neg number, make the binary num neg too { binaryNum = "-"; } // method call to convert decimal to binary binaryNum += DecToBin(decNum); // display data to user System.out.println("nThe integer value of "+ decNum + " = " + binaryNum + " in binary"); }// end of main public static String DecToBin(long decNum) { // use this string to save the binary number String binary = ""; if(decNum < 0) // if input is a neg number, make it positive { decNum *= -1; } // converts decimal to binary using division and modulus while(decNum > 0) { binary += (decNum % 2); decNum /= 2; } // return the reversed string to main return new StringBuffer(binary).reverse().toString(); }}// http://programmingnotes.org/

**QUICK NOTES:**

The highlighted lines are sections of interest to look out for.

Once compiled, you should get this as your output

Note: The code was compiled 3 separate times to display different output

`====== RUN 1 ======`

Welcome to My Programming Notes' Java Program.

Please enter an integer value: 5

The integer value of 5 = 101 in binary

====== RUN 2 ======

Welcome to My Programming Notes' Java Program.

Please enter an integer value: -25

The integer value of -25 = -11001 in binary

====== RUN 3 ======

Welcome to My Programming Notes' Java Program.

Please enter an integer value: 12345678910

`The integer value of 12345678910 = 1011011111110111000001110000111110 in binary`