I can only get correct output for decimal less than five. the output for five is 110 when it should be 101. the output for six is 101 and the output for ten is 1100.
//while loop divides each digit
while (decimal > 0)
{
//divides and digit becomes the remainder
int digit = decimal % 2;
//makes the digit into a string builder so it can be reversed
binaryresult.append(digit);
decimal = decimal / 2;
display.setText(binaryresult.reverse());
}
Usee the below code it may work for you
import java.util.Scanner;
public class decToBinary{
public String decToBin(int n) {
StringBuilder result = new StringBuilder();
int i = 0;
int b[] = new int[10];
while (n != 0) {
i++;
b[i] = n % 2;
n = n / 2;
}
for (int j = i; j > 0; j--) {
result.append(b[j]);
}
return result.toString();
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter decimal no :");
int n=sc.nextInt();
System.out.println("binary numbers is :");
decToBinary dtb = new decToBinary();
System.out.println(dtb.decToBin(n));
}
}
Something like this may be closer to what you are asking for:
while (decimal > 0) {
result.insert(0, (char) ((decimal % 2) + '0'));
decimal /= 2;
}
It uses insert to avoid reversing and adds the character instead of the number.
But you would be better off using a built in mechanism such as:
BigInteger.valueOf(decimal).toString(2)
i am not able to reproduce the behaviour using the following:
public static String decToBin(int n) {
StringBuilder result = new StringBuilder();
while (n > 0) {
int dec = n % 2;
result.append(dec);
n = n / 2;
}
return result.reverse().toString();
}
however, consider using the build-in
public static String decToBin(int n) {
return Integer.toBinaryString(n);
}
(or even BigInteger as stated above)
try this code , i hope this is what u r looking for:
public class DecimalToBinary {
public static void main(String[] args)
{
int decimal=11;
StringBuffer binaryValue=new StringBuffer();
while(decimal>0 ){
int rem=decimal%2;
decimal=decimal/2;
System.out.println("Remainder:"+rem);
binaryValue.append(rem);
}
System.out.println("binary is:"+binaryValue.reverse());
}
}
Related
Create a java program that reads an integer number (NUM) and determine its reverse by using the division and remainder/modulo operators. If the last digit is zero, replace it with a one(1) before reversing the number. Output also the sum of all the digits.
import java.util.*;
public class Main {
static int replace(int number){
if (number == 0)
return 0;
int digit = number % 10;
if (digit == 0)
digit = 1;
return (number/10) * 10 + digit;
}
static int Convert(int number){
if (number == 0)
return 0;
else
return replace(number);
}
public static void main(String[] args) {
int number;
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number : ");
number = kb.nextInt();
System.out.println("replace:"+replace(number));
int a, m = 0, sum = 0;
do{
a = replace(number) % 10;
m = m * 10 + a;
sum = sum + a;
number = replace(number) / 10;
}
while( replace(number) > 0);
System.out.println("Reverse:"+m);
System.out.println("Sum of digits:"+sum);
}
}
Currently the problem occurs in reversing the number because it also replace the last digit of the number, this should not happen.
Input/Output of current program
Enter the number : 2300
replace:2301
Reverse:1132
Sum of digits:7
do this instead
import java.util.*;
public class Main {
static int replace(int number){
if (number %10 == 0)
return number += 1;
return number;
}
static int Convert(int number){
if (number == 0)
return 0;
else
return replace(number);
}
public static void main(String[] args) {
int number;
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number : ");
number = kb.nextInt();
int a = 0, m = 0, sum = 0;
number = replace(number);
System.out.println("replace:" + number);
do{
a = number % 10;
m = m * 10 + a;
sum = sum + a;
number /= 10;
}
while( number > 0);
System.out.println("Reverse:"+m);
System.out.println("Sum of digits:"+sum);
}
}
Your code is fundamentally wrong because of the way you are replacing your numbers.
Changes made:
Changed replacing algorithm (You cannot change all 0 values to 1 that is wrong and why you got the wrong values)
Replace the number before you enter the loop. (You don't need to replace every iteration of the loop at 3 different place)
Expected output:
import java.util.Scanner;
import java.util.Arrays;
class Solve
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int i=0,count=0;
int[] arr = new int[10];
int n =in.nextInt();
while(n!=0)
{
arr[i]=n%2;
i++;
n=n/2;
}
System.out.println(Arrays.toString(arr));
}
}
}
I just want to calculate number of consecutive 1's. ? like 1110011001 will give me answer 5.. How can i do that??
System.out.println(Integer.toBinaryString(n).replaceAll("(0|(?<!1)1(?!1))", "").length());
The regex means: replace all 0's and any 1 not preceded or followed by another 1
You can handle this as a String [Edited to sum all consecutive 1's]:
String binary = in.nextLine();
String[] arrayBin = binary.split("0+"); // an array of strings without 0's
int result=0;
for (int i=0; i < arrayBin.length; i++){
if (arrayBin[i].length()<2){
result+=0;
}
else {
result+=arrayBin[i].length();
}
}
System.out.println("Total consecutive = "+result);
We can identify two consecutive binary ones in the least significant positions like this:
(value & 0b11) == 0b11
We can move the bits in value to the right like so:
value >>>= 1;
It's important to use tripple >>> over double >> because we don't care about the sign bit.
Then all we have to do is keep track of the number of consecutive 1s:
int count(int value) {
int count = 1;
int total = 0;
while (value != 0) {
if ((value & 0b11) == 0b11) {
count++;
} else {
if (count > 1) {
total += count;
}
count = 1;
}
value >>>= 1;
}
return total;
}
Test cases:
assertEquals(0, count(0b0));
assertEquals(0, count(0b1));
assertEquals(0, count(0b10));
assertEquals(2, count(0b11));
assertEquals(5, count(0b1110011));
assertEquals(5, count(0b1100111));
assertEquals(6, count(0b1110111));
assertEquals(7, count(0b1111111));
assertEquals(32, count(-1));
If you only want the length of the maximum, I have a similar answer: https://stackoverflow.com/a/42609478/360211
You can make use of Brian Kernighan’s Algorithm for counting the highest consecutive number of 1's.
A java pseudocode would be something like this
// Initialize result
int count = 0;
// Count the number of iterations to
// reach n = 0.
while (n!=0)
{
// This operation reduces length
// of every sequence of 1s by one.
n = (n & (n << 1));
count++;
}
public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
int counter = 0, max = Integer.MIN_VALUE;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 1){
counter += nums[i];
} else{
counter = nums[i];
}
max = Math.max(counter, max);
}
return max;
}
}
To this problem one trick which we can use here with help of some Java operators.
& operator and left shift (<<) in java.
Code snippet will be like :
public getConsecutiveCount(int inputNumber)
{
int count = 0 ;
while(inputNumber != 0)
{
inputNumber = inputNumber & (inputNumber << 1);
count++;
}
}
Explanation :
This function is taking input (ex : we want to check how many
consecutive 1's integer 6 have in its binary representation)
so out input number will be like :
inputNumber = ((110) & ((110)<<1)) {This left shift will result in 100 so final op :
110 & 100 which 100 , every time '0' is added to
our result and we iterate until whole number will
be zero and value of our count variable will be
our expected outcome }
To find Maximum consecutive 1's in binary(like 101)
int n = Convert.ToInt32(Console.ReadLine());
string[] base2=Convert.ToString(n,2).Split('0');
int count=0;
foreach(string s in base2)
count=s.Length>count?s.Length:count;
Console.WriteLine(count);
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String bs = Integer.toBinaryString(n);// bs=Binary String
char[] characters = bs.toCharArray();
int max = 1;
int temp = 1;
for (int i = 0; i < characters.length - 1; i++) {
if (characters[i] == characters[i + 1] & characters[i] == '1' & characters[i + 1] == '1') {
temp++;
if (temp > max) {
max = temp;
}
} else {
temp = 1;
}
}
System.out.println(max);
}
/* Given a decimal number print maximum number of consecutive 1's after binary conversion */
import java.io.*;
import java.util.*;
public class Solution {
public void countBinaryOne(int num){
int var =0, countOne= 0, maxCt=0;
while(num>0){
var= num%2;
if(var==1){
countOne=countOne+1;
}else{
if(maxCt<countOne){
maxCt= countOne;
countOne=0;
}else{
countOne=0;
}
}
num=num/2;
}
System.out.println(Math.max(countOne,maxCt));
}
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int n= in.nextInt();
Solution sol= new Solution();
sol.countBinaryOne(n);
}
}
public static void digitBinaryCountIfOne(int n){
int reminder=0, sum=0, total = 0;
while(n>0)
{
reminder = n%2;
n/=2;
if(reminder==1){
sum++;
if(sum>=total)
total=sum;
}else{
sum=0;
}
}
System.out.println(total);
}
I have created a converter which will hopefully convert any normal number which is inputted into a binary number, but it will only return the number "1" no matter what you input, why?
import java.util.Scanner;
public class NumtoBinary{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Number to binary converter");
int Num = sc.nextInt();
System.out.println(toBin(2));
}
public static int toBin(int Num){
int result = 0;
while(Num > 0){
int mod = Num % 2;
result = result * 1 + mod;
Num /= 2;
}
return result;
}
}
Your approach is close but for each iteration that produces zero for the mod you need to reflect that. You could use a String to track the result of each iteration and convert it to an integer for the return value like this:
public static int toBin(int Num) {
String result = "";
while (Num > 0) {
int mod = Num % 2;
result = mod + result;
Num /= 2;
}
return Integer.parseInt(result);
}
For example the method above if you input 12 then each iteration would build the string like this "0", "00", "100", "1100"
My program should convert decimal numbers to binary. For big numbers it is giving me a negative number not a binary number. Why is this?
For example, if I supply 2321 I get 100100010001, which is fine. But if I supply
241242141 I get -2127232070093227171.
I can't use strings, arrays, functions. There is another option without define it as string? the output?
import java.util.Scanner;
public class d {
public static void main(String[] args) {
long num = 0;
long temp = 0L;
Scanner sc = new Scanner(System.in);
num = sc.nextLong();
long place = 1L;
long output = 0;
//System.out.print(""+ num%2+ (num%2)%2);
while(num != 0) {
temp = num % 2;
num = num / 2;
output += (place*temp);
place *=10;
}
System.out.print(""+output);
}
}
You problem is here
output += (place*temp);
place *=10;
this is producing a number which overflows.
A simple alternative is to create a String instead of generating a number you will convert to a String anyway.
StringBuilder output = new StringBuilder();
while(num != 0) {
output.append(num & 1);
num >>>= 1;
}
System.out.print(output.reverse());
or even
StringBuilder output = new StringBuilder();
for(long num = sc.netLong(); num != 0; num >>>= 1)
output.append(num & 1);
System.out.print(output.reverse());
If you want to use no functions except input or output.
long num = 241242141;
int shift = 63;
while (num >>> shift == 0 && shift > 0) shift--;
for (; shift >= 0; shift--)
System.out.print((num >>> shift) & 1);
// for comparison only
System.out.println("\n"+Long.toBinaryString(num));
prints
1110011000010001000000011101
1110011000010001000000011101
The problem is that, you are storing your Binary Equivalent in a long type, which cannot store such a long values.
You should rather use a StringBuilder and append your remainder - temp in it.
Then print it in reverse: -
StringBuilder builder = new StringBuilder();
while(num != 0) {
temp = num % 2;
num = num / 2;
builder.append(temp);
output += (place*temp);
place *=10;
}
System.out.println(builder.reverse());
If you don't need to use any methods, then just use String Concatenation, and then a loop to print the string in reverse: -
String builder = "";
while(num != 0) {
temp = num % 2;
num = num / 2;
builder += temp;
output += (place*temp);
place *=10;
}
for (int i = builder.length() - 1; i >= 0; i--) {
System.out.print(builder.charAt(i));
}
But, beware, this will create a large number of String objects on Heap. Also, here you are using a charAt method, that you have to use.
With recursion:
public class d {
static void toBinaryString( long number )
{
if( number > 1 ) toBinaryString( number / 2L );
System.out.print( number % 2L );
}
public static void main(String[] args) {
long num = 241242141L;
System.out.println( Long.toBinaryString( num ));
toBinaryString( num );
}
}
The ouput:
1110011000010001000000011101
1110011000010001000000011101
I tried to find the factorial of a large number e.g. 8785856 in a typical way using for-loop and double data type.
But it is displaying infinity as the result, may be because it is exceeding its limit.
So please guide me the way to find the factorial of a very large number.
My code:
class abc
{
public static void main (String[]args)
{
double fact=1;
for(int i=1;i<=8785856;i++)
{
fact=fact*i;
}
System.out.println(fact);
}
}
Output:-
Infinity
I am new to Java but have learned some concepts of IO-handling and all.
public static void main(String[] args) {
BigInteger fact = BigInteger.valueOf(1);
for (int i = 1; i <= 8785856; i++)
fact = fact.multiply(BigInteger.valueOf(i));
System.out.println(fact);
}
You might want to reconsider calculating this huge value. Wolfram Alpha's Approximation suggests it will most certainly not fit in your main memory to be displayed.
This code should work fine :-
public class BigMath {
public static String factorial(int n) {
return factorial(n, 300);
}
private static String factorial(int n, int maxSize) {
int res[] = new int[maxSize];
res[0] = 1; // Initialize result
int res_size = 1;
// Apply simple factorial formula n! = 1 * 2 * 3 * 4... * n
for (int x = 2; x <= n; x++) {
res_size = multiply(x, res, res_size);
}
StringBuffer buff = new StringBuffer();
for (int i = res_size - 1; i >= 0; i--) {
buff.append(res[i]);
}
return buff.toString();
}
/**
* This function multiplies x with the number represented by res[]. res_size
* is size of res[] or number of digits in the number represented by res[].
* This function uses simple school mathematics for multiplication.
*
* This function may value of res_size and returns the new value of res_size.
*/
private static int multiply(int x, int res[], int res_size) {
int carry = 0; // Initialize carry.
// One by one multiply n with individual digits of res[].
for (int i = 0; i < res_size; i++) {
int prod = res[i] * x + carry;
res[i] = prod % 10; // Store last digit of 'prod' in res[]
carry = prod / 10; // Put rest in carry
}
// Put carry in res and increase result size.
while (carry != 0) {
res[res_size] = carry % 10;
carry = carry / 10;
res_size++;
}
return res_size;
}
/** Driver method. */
public static void main(String[] args) {
int n = 100;
System.out.printf("Factorial %d = %s%n", n, factorial(n));
}
}
Hint: Use the BigInteger class, and be prepared to give the JVM a lot of memory. The value of 8785856! is a really big number.
Use the class BigInteger. ( I am not sure if that will even work for such huge integers )
Infinity is a special reserved value in the Double class used when you have exceed the maximum number the a double can hold.
If you want your code to work, use the BigDecimal class, but given the input number, don't expect your program to finish execution any time soon.
The above solutions for your problem (8785856!) using BigInteger would take literally hours of CPU time if not days. Do you need the exact result or would an approximation suffice?
There is a mathematical approach called "Sterling's Approximation
" which can be computed simply and fast, and the following is Gosper's improvement:
import java.util.*;
import java.math.*;
class main
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int i;
int n=sc.nextInt();
BigInteger fact = BigInteger.valueOf(1);
for ( i = 1; i <= n; i++)
{
fact = fact.multiply(BigInteger.valueOf(i));
}
System.out.println(fact);
}
}
Try this:
import java.math.BigInteger;
public class LargeFactorial
{
public static void main(String[] args)
{
int n = 50;
}
public static BigInteger factorial(int n)
{
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++)
result = result.multiply(new BigInteger(i + ""));
return result;
}
}
Scanner r = new Scanner(System.in);
System.out.print("Input Number : ");
int num = r.nextInt();
int ans = 1;
if (num <= 0) {
ans = 0;
}
while (num > 0) {
System.out.println(num + " x ");
ans *= num--;
}
System.out.println("\b\b=" + ans);
public static void main (String[] args) throws java.lang.Exception
{
BigInteger fact= BigInteger.ONE;
int factorialNo = 8785856 ;
for (int i = 2; i <= factorialNo; i++) {
fact = fact.multiply(new BigInteger(String.valueOf(i)));
}
System.out.println("Factorial of the given number is = " + fact);
}
import java.util.Scanner;
public class factorial {
public static void main(String[] args) {
System.out.println("Enter the number : ");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
factorial f=new factorial();
int result=f.fact(n);
System.out.println("factorial of "+n+" is "+result);
}
int fact(int a)
{
if(a==1)
return 1;
else
return a*fact(a-1);
}
}