How can we create a smallest binary number whose length is given.
For example,
the smallest binary number of length 4 is 1000
the smallest binary number of length 3 is 100.
I am not able to come up with any algorithm since length is only given.
This process of creating the number is to be done
numerous time with varying length.
What can be the code for that?
That is easy: 0, 00, 000, 0000, 00000, ....
On the serious note, binary is just another notation. What you have is a simple computation like this
binary 1 = decimal 1
binary 10 = decimal 2
binary 100 = decimal 4
binary 1000 = decimal 8
So you can do
int myNumber = 1;
for (int i = 1; i < LENGTH; i++)
myNumber = myNumber * 2;
Or use
myNumber = Math.pow(2, LENGTH - 1);
Related
The task is to find lost element in the array. I understand the logic of the solution but I don't understand how does this formula works?
Here is the solution
int[] array = new int[]{4,1,2,3,5,8,6};
int size = array.length;
int result = (size + 1) * (size + 2)/2;
for (int i : array){
result -= i;
}
But why we add 1 to total size and multiply it to total size + 2 /2 ?? In all resources, people just use that formula but nobody explains how that formula works
The sum of the digits 1 thru n is equal to ((n)(n+1))/2.
e.g. for 1,2,3,4,5 5*6/2 = 15.
But this is just a quick way to add up the numbers from 1 to n. Here is what is really going on.
The series computes the sum of 1 to n assuming they all were present. But by subtracting each number from that sum, the remainder is the missing number.
The formula for an arithmetic series of integers from k to n where adjacent elements differ by 1 is.
S[k,n] = (n-k+1)(n+k)/2
Example: k = 5, n = 10
S[k,n] = 5 6 7 8 9 10
S[k,n] = 10 9 8 7 6 5
S[k,n] = (10-5+1)*(10+5)/2
2S[k,n] = 6 * 15 / 2
S[k,n] = 90 / 2 = 45
For any single number missing from the sequence, by subtracting the others from the sum of 45, the remainder will be the missing number.
Let's say you currently have n elements in your array. You know that one element is missing, which means that the actual size of your array should be n + 1.
Now, you just need to calculate the sum 1 + 2 + ... + n + (n+1).
A handy formula for computing the sum of all integers from 1 up to k is given by k(k+1)/2.
By just replacing k with n+1, you get the formula (n+1)(n+2)/2.
It's simple mathematics.
Sum of first n natural numbers = n*(n+1)/2.
Number of elements in array = size of array.
So, in this case n = size + 1
So, after finding the sum, we are subtracting all the numbers from array individually and we are left with the missing number.
Broken sequence vs full sequence
But why we add 1 to total size and multiply it to total size + 2 /2 ?
The amount of numbers stored in your array is one less than the maximal number, as the sequence is missing one element.
Check your example:
4, 1, 2, 3, 5, 8, 6
The sequence is supposed to go from 1 to 8, but the amount of elements (size) is 7, not 8. Because the 7 is missing from the sequence.
Another example:
1, 2, 3, 5, 6, 7
This sequence is missing the 4. The full sequence would have a length of 7 but the above array would have a length of 6 only, one less.
You have to account for that and counter it.
Sum formula
Knowing that, the sum of all natural numbers from 1 up to n, so 1 + 2 + 3 + ... + n can also be directly computed by
n * (n + 1) / 2
See the very first paragraph in Wikipedia#Summation.
But n is supposed to be 8 (length of the full sequence) in your example, not 7 (broken sequence). So you have to add 1 to all the n in the formula, receiving
(n + 1) * (n + 2) / 2
I guess this would be similar to Missing Number of LeetCode (268):
Java
class Solution {
public static int missingNumber(int[] nums) {
int missing = nums.length;
for (int index = 0; index < nums.length; index++)
missing += index - nums[index];
return missing;
}
}
C++ using Bit Manipulation
class Solution {
public:
int missingNumber(vector<int> &nums) {
int missing = nums.size();
int index = 0;
for (int num : nums) {
missing = missing ^ num ^ index;
index++;
}
return missing;
}
};
Python I
class Solution:
def missingNumber(self, nums):
return (len(nums) * (-~len(nums))) // 2 - sum(nums)
Python II
class Solution:
def missingNumber(self, nums):
return (len(nums) * ((-~len(nums))) >> 1) - sum(nums)
Reference to how it works:
The methods have been explained in the following links:
Missing Number Discussion
Missing Number Solution
I am trying to make a converter that converts decimal into binary, there is a catch tho, I can't use any other loops or statements except
while (){}
And I can't figure out how to start subtracting the number that fits into the decimal when it can and not using any if statements. Does anyone have any suggestions?
import java.util.Scanner;
public class Converter{
static Scanner input = new Scanner (System.in);
public static void main (String[] args){
System.out.println ("What is the number in the decimal system that you want to convert to binary?");
int dec = input.nextInt();
int sqr = 1024;
int rem;
while (dec != 0){
rem = dec / sqr;
sqr = sqr / 2;
System.out.print(rem);
}
}
}
Try this:
import java.util.Scanner;
public class Converter {
public static void main(String[] args) {
final Scanner input = new Scanner(System.in);
System.out.println("What is the number in the decimal system that you want to convert to binary?");
int dec = input.nextInt();
int div = 128;
while (div > 0) {
System.out.print(dec / div);
dec = dec % div;
div >>= 1; // equivalent to div /= 2
}
System.out.println();
}
}
Now, let's go through the code and try to understand what's going on. I'm assuming that the maximum size is 8 bits, so the variable div is set to 2n-1 where n = 1. If you need 16 bits, div would be 32768.
The programme starts from that value and attempts to do an integer division of the given number by the divider. And the nice thing about it is that it will yield 1 if the number is greater than or equal to the divider, and 0 otherwise.
So, if the number we're trying to convert is 42, then dividing it by 128 yields 0, so we know that the first digit of our binary number is 0.
After that, we set the number to be the remainder of the integer division, and we divide the divider by two. I'm doing this with a bit shift right (div >>= 1), but you could also use a divider-assignment (div /= 2).
By now, the divider is 64, and the number is still 42. If we do the operation again, we again get 0.
At the third iteration, we divide 42 by 32, and this yields 1. So our binary digits so far are 001. We set the number to be the remainder of the division, which is 10.
Continuing this, we end up with the binary number 00101010. The loop ends when the divider div is zero and there's nothing left to divide.
Try to understand, step by step, how the programme works. It's simple, but it can be very difficult to come up with a simple solution. In this case, it's applied mathematics, and knowing how integer maths work in Java. That comes with experience, which you'll get in due time.
Your code has some Problem. It is more easier to convert a decimal to binary. fro example:
int num = 5;
StringBuilder bin = new StringBuilder();
while (num > 0) {
bin.append(num % 2);
num /= 2;
}
System.out.println(bin.reverse());
I use StringBuilder to reverse my String and I prefer String because length of binary can be anything. if you use int or long, maybe overflow happen.
Update
if you you want to use primitive types only, you can do something like this but overflow may happen:
long reversedBin = 0, Bin = 0;
while (n > 0) {
reversedBin = reversedBin * 10 + (n % 2);
n /= 2;
}
while (reversedBin > 0) {
Bin = Bin * 10 + (reversedBin % 10);
reversedBin /= 10;
}
System.out.println(Bin);
Remember the algorithm to convert from decimal to binary.
Let n be a number in decimal representation:
digit_list = new empty stack
while n>0 do
digit = n%2
push digit in stack
n = n/2
end while
binary = new empty string
while digit_list is not empty do
character = pop from stack
append character to binary
end while
Java provides a generic class Stack that you can use as a data structure. You could also use lists, but remember to take the digits in the inverse order you have calculated them.
find the base 2 log of the number and floor it to find the number of bits needed. then integer divide by that bits place in 2's power and subtract that from the original number repeat until 0. doesn't work for negative. there are better solutions but this one is mine
int bits = (int) Math.floor(Math.log((double) dec) / Math.log((double) 2));
System.out.println("BITS:" + bits);
while (dec > 0) {
int twoPow = (int) Math.pow((double) 2, (double) bits);
rem = dec / twoPow;
dec = dec - rem * twoPow;
bits--;
System.out.print(rem);
}
I'm a novice Java coder working on a problem dealing with counting consecutive integers in the binary forms of numbers.
The numbers are read from the input, and converted to binary using the method called conversion. The binary form is then sent to a character array where the for loop checks for consecutive characters(specifically the number 1) and prints the maximum count as the final answer.
I've managed to get the code to a state where I feel it should be working, but I've only had success with about half of the test cases. The larger number conversions like 262,141 tend to produce incorrect answers. Can anyone tell me where I've gone wrong?
I have a suspicion that it's something to do with the character array, but after several hours of research I haven't been able to find a solution to my particular problem.
import java.io.*;
import java.util.*;
public class Solution {
public static int conversion(int decimal){//this will take the decimal from the input and convert it to binary
int result = 0;//the result from each step of the conversion
int base = 1;//used to multiply the remainder by 1, 10, 100 etc
while(decimal > 0){
int remainder = decimal % 2;//takes the remainder of the iteration
decimal = decimal / 2;//halves the decimal number
result = result + (remainder * base);//pseudo concatenation of the binary
base = base * 10;//increases the base multiplier to continue filling out the binary leftward
}
return result;//returns result after loop has finished
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();//scan the input to obtain the decimal number
int binaryForm = conversion(n);//convert the decimal to binary and assign to binaryForm variable
String stringForm = Integer.toString(binaryForm);//convert binaryForm to a String
int counter = 1;
int max = 1;
char testArray[] = stringForm.toCharArray();//send stringForm to fill out testArray
for(int i = 0; i < testArray.length - 1; i++){//loops through testArray to test stringForm values
if(testArray[i] == testArray[i + 1] && testArray[i] == '1'){//if consecutive values equal char 1, increase counter
counter += 1;
if(counter > max){
max = counter;//if counter is higher than current maxCounter, increase maxCounter
}
}
else {//if consecutive values do not equal 1, reset counter
counter = 1;
}
}
System.out.print(max);//print the maximum consecutive values for the decimal input when converted to binary
}
}
You are trying to create a binary representation of a decimal number using an integer. This will work for smaller numbers but it doesn't take long for you to reach an overflow. You should use a string representation of the binary number like so
String numBin = "";
while(num > 0)
{
numBin = num % 2 + numBin;
num = num / 2;
}
System.out.println("Binary Representation: " + numBin);
Then take that string and loop through it calculating the consecutive counts of 1's
int consecutiveCount = 0;
for(int i = 0; i < numBin.length() - 1; i++)
{
if(numBin.charAt(i) == '1' && numBin.charAt(i + 1) == '1')
{
consecutiveCount++;
}
}
System.out.println("Consecutive Count: " + consecutiveCount);
Output
Number: 261141
Binary Representation: 111111110000010101
Consecutive Count: 7
Number: 3
Binary Representation: 11
Consecutive Count: 1
Number: 18
Binary Representation: 10010
Consecutive Count: 0
Number: 1111111
Binary Representation: 100001111010001000111
Consecutive Count: 5
I hava see this code in HashMap:
/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}
The HashMap has this document:
when length is a power of two then h & (length-1) is equals h%length
I want to know the principle in math
just is why h & (length-1) == h%length (length is a power of two)
First you can think what it looks like when you take any integer n mod power of 2.
WLOG let this power of 2 is 10000 in binary (indeed it must be of the form 100...0), what does its multiples looks like? Its multiples must look like...whatever digit...0000. The last 4 digit must be zero.
So what is a number n mod 10000? Let this number n be ...whatever digit...1011. This number can be expressed as ...whatever digit...0000 + 1011, now it is obvious that n mod 10000 indeed only the last 4 digits is left.
In general, let length be a power of 2 which has x zeros, then n%length is the least x significant digits of n
So legnth - 1is indeed 111..111 (x digit 1), and when you take bitwise and with the number n, the least x significant digits of n is preserved and returned, which is what we want. Using the same example above,
Length = 10000, Length - 1 = 1111
n = 101001101 = 101000000 + 1101
=> n % Length = 1101
n & (Length - 1) = 1101
= n % Length
Just imagine: any power of two contains single bit set and has binary representation like this:
l = 00010000
if you subtract 1, it will contain ones at the right places
m = l-1 = 00001111
binary AND operation with any h makes all most significant bits zero, leaving less significant ones
10101010 & 00001111 = 00001010
This is equivalent to modulo operation with modulo l
How can I count the 0s after a decimal point? For example, 0.0003 has 3 zeros, 0.03 has 1 zero and 0.00000045 has 6 zeros.
One approach is to keep multiplying by 10 until your number is greater than one; then count how many times you had to multiply by 10 and subtract 1.
double num = 0.00000045;
int zeros = 0;
while (num < 1) {
num *= 10;
zeros++;
}
zeros -= 1;
System.out.println(zeros);
6
If you have other non-zero digits before the decimal point, you can trim those off with something like num = num % 1. If your number is negative, then just take its absolute value.
(int)Math.log10(1/(x%1))
I think this short formula should work correct [for positive x - if it can be negative, we add taking of absolute value] - or there are some cases when it doesn't?
You could do this using Strings. First get a substring of digits after decimal point. Then convert that into a char array. Then loop through it and count the number of zeroes.