Converting int to string in java is giving the answer as 1 - java

I converted a decimal integer to binary and that binary integer when I'm trying to convert to a string is giving me 1 as the answer always when it should give the value of the string.
while(a>0)
{
b = a%2;
n = b;
a = a/2;
System.out.print(n);
}
String m = Integer.toString(n);
System.out.print(m);
Any corrections and suggestions would be much appreciated.
Thanks!

On every loop step, you have these two statements:
b = a % 2;
n = b;
Think about why all the possible values of n are 0 and 1?
It's because n copies the value of b, which is the value of a modulo 2, which is always 0 or 1.
The last value of n will be the left-most bit of the binary representation of a, which will be always 1 (unless a is 0) and this is why you always get 1 when printing m.

When you use
n = b;
you are replacing the value of n each time. What you want it to accumulate the bits in n. The simplest way to do this is to use a StringBuilder.
StringBuilder sb = new StringBuilder();
while (a > 0) {
int lowest = a & 1;
sb.insert(0, lowest);
a = a >>> 1; // shift the bits down by 1.
}
String m = sb.toString();
System.out.print(m);
This will do the same thing as Integer.toString(a, 2)

Related

Mathematically calculating decimal to binary (java)

I am having issue with my algorithms to convert a decimal number to a binary number without using parsing, this is the relevant section of code:
public static void dtb(){
System.out.print("\nDenary number to convert?(lower than 255): "); //eight bit conversion
int num = sc.nextInt();
int decVal = 128;
int saveNum = num; //save point for the first input
int[] arr;
arr = new int[8];
do{
if (num - decVal > 0){ //binary to decimal
num = num - decVal;
arr[x] = 1;
} else arr[x] = 0;
decVal = decVal / 2;
x++;
} while (decVal != 1);
System.out.print("\nBinary value of "+saveNum+" is: "+arr[0]+arr[1]+arr[2]+arr[3]+arr[4]+arr[5]+arr[6]+arr[7]);
}
x is declared initialized statically, therefore out of view.I also know where the error is but I cant work out the right way to do it, hence the ask for help. I am also fairly new so any help on other method will be appreciated. Thank you for any help.
Example of output = (input=42) 00101000
You need to compare whether num - decVal is greater than or equal to 0. Because you have >, you are missing the case then it's equal to 0 and you're missing a 1 bit.
if (num - decVal >= 0){
Also, you'll need to loop while decVal is not equal to 0, instead of 1, or else you'll miss the last bit on odd numbers.
} while (decVal != 0);
Output with changes:
Binary value of 42 is: 00101010
Binary value of 43 is: 00101011

Get first N digits of a number

I'm writing a small program that displays the factorial of a number.
When I enter the number 20 I got the number 2432902008176640000 as result.
How can I limit a decimal number in Java.
For example the number 2432902008176640000 should be 2432 (limit 4).
Thanks in advance.
The following might do what you want, if what you want to do is what I think you want to do:
long n = 2432902008176640000L; // original number
while (n > 9999) {
// while "more than 4 digits", "throw out last digit"
n = n / 10;
}
// now, n = 2432
And a demo.
Notes:
A long can only represent values as large as 9223372036854775807 (which is only about 4 times as large as the number given) before it will overflow. If dealing with larger numbers you'll need to switch to BigInteger or similar. The same technique can be used, updated for syntax differences.
As fge pointed out, this won't work as it is written over negative numbers; this can be addressed by either changing the condition (i.e. n < -9999) or first obtaining the absolute value of n (and then reverting the operation at the end).
As done in yinqiwen's answer, n > 9999 can be replaced with n >= (long)Math.pow(10, N) (preferably using a temporary variable), where N represents the number of decimal digits.
Replace N by the limit.
long v = 2432902008176640000L;
long x = (long) Math.pow(10, N);
while(v >= x)
{
v /= 10;
}
Try this, may help:
Long n = 2432902008176640000;
String num = String.valueOf(n);
num = num.subString(0, 4);
n = Long.valueOf(num);
I am assuming you mean factorial of a number.
Just convert the number into a string and use substring method to get first 4 digits only.
fact is the factorial value
String result_4_str=(fact+"").substring(0, 4);
long result_4 = Long.parseLong(result_4_str);
System.out.println(result_4);
Some of the previous answers with loops are O(n) time complexity. Here's a solution for constant time complexity:
long num = 2432902008176640000L;
int n = 4;
long first_n = (long) (num / Math.pow(10, Math.floor(Math.log10(num)) - n + 1));
You can try
long number = 2432902008176640000L ;
String numberStr = String.valueOf(number);
if(numberStr.length()>=4){
System.out.println(numberStr.substring(0, 4));
}

Want to Convert decimal value in 2 raised to format and want to know its power of 2 in java

I have one decimal value like 65 and I want to divide this value in 2 raised to format.
For example, I have this type rule:
If I get 42 as a decimal number, I want to divide first 42 number in format of 2 raised to. Then, I want to output its power only, like:
OutPut : 1,3,5
For example, if I have 65 as a decimal number, then I want 6,0 as its output, because (2 raised to 6) + (2 raised to 0) = 65.
Thanks
Anybody can help me how I can achieve this thing in Java.
You can repeatedly compare the least significant bit, counting as you go, and right-shifting the number to look at each bit in turn:
int n = 65
int d = 0;
while (n > 0) {
if ((n & 1) == 1) { // check LSB
System.out.println(d);
}
n >>>= 1; // shift right
++d; // inc digit count
}
Integer.toString(65, 2);
Does the following output:
1000001
Then you work on the String.
This can be improved, but I think it'll do the job.
int n = 42;
String binary = Integer.toBinaryString(n);
for(int i = binary.length() - 1; i >= 0; i--){
if(binary.charAt(i) == '1')
System.out.print(i+1);
}
Here is the algorithm:
Find a log base 2 of given number x=log(2, input)
Find the floor and the ceiling of the result y = floor(x), z=ceiling(x)
Find 2^y, 2^z and choose the one closer to the input.
calculate the diff = (input - 2^(x or y)) and do the same for the diff recursively until dif=0.

about Java BigInteger

I'm new to Java and just code a program with BigInteger.
public static void main(String[] args) {
BigInteger n = new BigInteger("5");
BigInteger i = new BigInteger("2");
while (lesserOrEqual(i,n) {
System.out.println("n.mod(i) = "+n.mod(i));
if (n.mod(i) == ZERO) {
n = n.divide(i);
}
else {
i.add(ONE);
}
System.out.println("n = "+n);
System.out.println("i = "+i);
}
public static boolean lesserOrEqual(BigInteger m, BigInteger n) `{
if (m.compareTo(n) == -1 || m.compareTo(n) == 0)
return true;
return false;
}
ZERO and ONE are defined of the type BigInteger 0, 1, respectively.
I want "i=2" to divide "n=5", if "n mod i == 0", else "i++", until "n" to be lesser or equal to "i".
I think the output must be
n.mod(i) = 1
n = 5
i = 3
n.mod(i) = 2
n = 5
i = 4
n.mod(i) = 1
n = 5
i = 5
n.mod(i) = 0
n = 1
i = 5
and with the equivalent code with primitive type int, I have the result as expected.
but this with BigInteger goes to infinite loop
n.mod(i) = 1
n = 5
i = 2
...
Does anyone know why it is so?
The BigInteger class represents integers as immutable objects.
There are two points here.
Don't use == to test if two BigIntegers are equal
To change the value of a BigInteger variable you must do i = i.add(ONE); and not just i.add(ONE);.
The reason not to use == to compare BigIntegers is because instead of checking for numerical equality you are checking that they are the same object in memory.
Consider with Strings.
String a = "a";
String b = "b";
String x = a + b;
String y = "ab";
In the above example x.equals(y) is true because they contain the same number of characters in exactly the same order. However, x == y is not true because they are different objects in memory.
The reason you need to to assign the result of arithmetic operations to a variable is because BigInteger is immutable. Thus arithmetic operations cannot change the value of the object it is operating on, but it can create a new BigInteger (which it returns). Which is why you must assign the result of the arithmetic operation to the variable you want it saved in.
As an aside a shortcut for your lesserThanOrEqual to is this.
boolean result = m.compareTo(n) <= 0;
Basically
m == n becomes m.compareTo(n) == 0
m != n becomes m.compareTo(n) != 0
m < n becomes m.compareTo(n) < 0
m > n becomes m.compareTo(n) > 0
m <= n becomes m.compareTo(n) <= 0
m >= n becomes m.compareTo(n) >= 0
both of the above answers are right. They are not telling you, however, that BigInteger instances are immutable. That means they don't change once set. That is why you need to always assign the result of a transformation...
You are doing this:
i.add(ONE);
But you should do this:
i = i.add(ONE);
You're not saving the result that gets returned from i.add(ONE). It's giving you a BigInteger object containing the desired value, but you're dropping it on the floor instead of assigning it to i.
i.add(ONE) has to be reassigned: i = i.add(ONE)

How do I determine number of bytes needed to represent a given integer?

I need a function in Java to give me number of bytes needed to represent a given integer. When I pass 2 it should return 1, 400 -> 2, 822222 -> 3, etc.
#Edit: For now I'm stuck with this:
numOfBytes = Integer.highestOneBit(integer) / 8
Don't know exactly what highestOneBit() does, but have also tried this:
numOfBytes = (int) (Math.floor(Math.log(integer)) + 1);
Which I found on some website.
static int byteSize(long x) {
if (x < 0) throw new IllegalArgumentException();
int s = 1;
while (s < 8 && x >= (1L << (s * 8))) s++;
return s;
}
Integer.highestOneBit(arg) returns only the highest set bit, in the original place. For example, Integer.highestOneBit(12) is 8, not 3. So you probably want to use Integer.numberOfTrailingZeros(Integer.highestOneBit(12)), which does return 3. Here is the Integer API
Some sample code:
numOfBytes = (Integer.numberOfTrailingZeroes(Integer.highestOneBit(integer)) + 8) / 8;
The + 8 is for proper rounding.
The lazy/inefficient way to do this is with Integer#toBinaryString. It will remove all leading zeros from positive numbers for you, all you have to do is call String#length and divide by 8.
Think about how to solve the same problem using normal decimal numbers. Then apply the same principle to binary / byte representation i.e. use 256 where you would use 10 for decimal numbers.
static int byteSize(long number, int bitsPerByte) {
int maxNumberSaveByBitsPerByte = // get max number can be saved by bits in value bitsPerByte
int returnValue = getFloor(number/maxNumberSaveByBitsPerByte); // use Math lib
if(number % maxNumberSaveByBitsPerByte != 0)
returnValue++;
return returnValue;
}
For positive values: 0 and 1 need 1 digit, with 2 digits you get the doubled max value, and for every digit it is 2 times that value. So a recursive solution is to divide:
public static int binaryLength (long l) {
if (l < 2) return 1;
else 1 + binaryLength (l /2L);
}
but shifting works too:
public static int binaryLength (long l) {
if (l < 2) return 1;
else 1 + binaryLength (l >> 1);
}
Negative values have a leading 1, so it doesn't make much sense for the question. If we assume binary1 is decimal1, binary1 can't be -1. But what shall it be? b11? That is 3.
Why you wouldn't do something simple like this:
private static int byteSize(int val) {
int size = 0;
while (val > 0) {
val = val >> 8;
size++;
}
return size;
}
int numOfBytes = (Integer.SIZE >> 3) - (Integer.numberOfLeadingZeros(n) >> 3);
This implementation is compact enough while performance-friendly, since it doesn't involve any floating point operation nor any loop.
It is derived from the form:
int numOfBytes = Math.ceil((Integer.SIZE - Integer.numberOfLeadingZeros(n)) / Byte.SIZE);
The magic number 3 in the optimized form comes from the assumption: Byte.SIZE equals 8

Categories

Resources