decimal to binary conversion java - java

My method seems to only work for all int less than 2^10. If it is greater than or equal to this value then it just returns 2^32. I'm not sure how my program is even getting this. I need to make it work for all int less than or equal to 2^15. Can anybody at least see why it's returning 2^32 for int greater than or equal to 2^10? If so then let me know please.
public static int DecToBin(int num) {
int binNum = 0;
int divisor = num;
int mod = 0;
int exp =0;
while(divisor != 0){
mod = divisor%2;
divisor = divisor/2;
if(mod==1){
binNum = (int) (binNum + (Math.pow(10, exp)));
}
exp++;
}
return binNum;
}

An always easy way to accomplish this is:
Integer.toBinaryString(int);
This is the easiest way to do this but their might be more efficiant ways to do it.
Hopefully this is what you were looking for

As Taco pointed out, you can call Integer.toBinaryString(int), but if this is for an assignment or something where you should write the method yourself, here is what I would do.
I would write a method, that will constantly divide the number by 2, and store the remainders in a String. Something like this:
String binaryString = "";
int value = 100;
while(value > 0){
int remainder = value % 2;
value = value/2;
binaryString = remainder + binaryString;
}
I tested this in a quick console run and it produced '1100100' which is correct.
EDIT I used this as a reference.

Related

How to calculate the number of zeros in binary?

Hi I am making a method that can take an integer as a parameter and compute how many zeros its binary form has. So for example, if I have binaryZeros(44), its binary form is 101100. Therefore, binaryZeros(44) should return 3. However, I am making some errors and I cannot tell where it is coming from. I would appreciate it if someone can point out where I am making that error, or if my approach (logic) to this problem is good enough. Thank you!
My code is Below:
public static int binaryZeros(int n) {
int zeroCount = 0;
double m = n;
while (m >= 0.0) {
m = m / 2.0;
if (m == Math.floor(m)) {
zeroCount++;
} else {
m = Math.floor(m);
}
}
return zeroCount;
}
Below is a more concise way to solve this problem
public static int binaryZeros(int n) {
int zeroCount = 0;
// Run a while loop until n is greater than or equals to 1
while(n >= 1)
{
/* Use modulo operator to get the reminder of division by 2 (reminder will be 1 or 0 as you are dividing by 2).
Keep in mind that binary representation is an array of these reminders until the number is equal to 1.
And once the number is equal to 1 the reminder is 1, so you can exit the loop there.*/
if(n % 2 == 0)
{
zeroCount++;
}
n = n / 2;
}
return zeroCount;
}
Your approach is good, but I think there's a better way to do it. The Integer class has a static method that returns the binary of a number: Integer.toBinaryString(num) . This will return a String.
Then, you can just check if there are any 0 in that string with method that has a for loop and evaluating with an if:
public int getZeros(String binaryString){
int zeros = 0;
for(int i=0; i < binaryString.length; i++)
if(binaryString.charAt[i].equals('0')
zeros++;
return zeros;
}
I believe this would be a simpler option and it doesn't have any errors.
Once m == 0.0, it will never change, so your while loop will never stop.
If you start with a number m >= 0, it can never become negative no matter how many times you divide it by 2 or use Math.floor. The loop should stop when m reaches 0, so change the condition to while (m > 0.0).
Note that you could do the same thing with built-in standard library methods. For example, there is a method that returns the number of leading zeros in a number, and a method that returns the number of bits set to 1. Using both you can compute the number of zeros that are not leading zeros:
static int binaryZeros(int n) {
return Integer.SIZE - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n);
}
Here is one way. It simply complements the integer reversing 1's and 0's and then counts the 1 bits. You should not be using floating point math when doing this.
~ complements the bits
&1 masks the low order bit. Is either 1 or 0
>>> shifts right 1 bit including sign bit.
System.out.println(binaryZeros(44) + " (" +Integer.toBinaryString(44) +")");
System.out.println(binaryZeros(-44) + " ("Integer.toBinaryString(-44)+")");
public static int binaryZeros(int v) {
int count = 0;
while (v != 0) {
// count 1 bits
// of ~v
count += (~v)&1;
v >>>=1;
}
return count;
}
Prints
3 (101100)
4 (11111111111111111111111111010100)
Just be simple, whe there's Integer.bitCount(n) method:
public static int binaryZeros(int n) {
long val = n & 0xFFFFFFFFL;
int totalBits = (int)(Math.log(val) / Math.log(2) + 1);
int setBits = Long.bitCount(val);
return totalBits - setBits;
}
public static int getZeros(int num) {
String str= Integer.toBinaryString(num);
int count=0;
for(int i=0; i<str.length(); i++) {
if(str.charAt(i)=='0') count++;
}
return count;
}
The method toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string.
Then the for loop counts the number of zeros in the String and returns it.

How do I replace the first three characters of a Java integer by 111?

I have an integer in java. How do I replace its’ first three numbers with 111(or any other number), for example turning 783729 into 111729?
Many thanks!
You could convert it into a string and then replace the first three letters.
String s = String.valueOf(783729);
int i = Integer.parseInt(s.replace(s.substring(0, 3), "111"));
Convert the integer to string replace the first three characters and convert it back to integer.kindly try to do it yourself. if you feel stuck during coding post your code along with the problem you face.
You can do this without converting to a string using simple arithmetic:
// Assumes that num is initially at least 999.
int replaceWith111(int num) {
if (num < 1000) {
return 111;
}
return 10 * replaceWith111(num / 10) + (num % 10)
}
Obviously if you just need to get this done you'd convert to String and do the substitution there.
However, just for fun, here's how you could do it using only Math functions and operators. Doesn't handle negative numbers - that's left as an exercise fo the reader :)
int s = 111;
int n = 783729;
int ds = (int)Math.ceil(Math.log10(s));
int dn = (int)Math.ceil(Math.log10(n));
int b = (int)Math.pow(10, dn-ds);
int sn = s * b + n % b;
System.out.println(sn);
Output:
111729

How can I tell that an integer is only 2 digits long?

I need to write a Java program that prompts the user to enter an integer consisting of exactly 2 digits; then displays on the screen the sum of its individual digits.
I am stuck here. What am I doing wrong?
import java.util.Scanner ;
public class ss {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int x;
System.out.println("Please Enter a number consists of 2 digits only : ");
x = input.nextInt();
x.length() == 2;
}
}
and the last line contains an error!
Assuming that x is positive, a simple way to check if it has exactly two digits would be:
if (x >= 10 && x <= 99) {
// x contains exactly two digits
}
The variable x is of type int, so you can't call a method on it. You need to either read the input as a String or convert the int to a String then call length(), or just test that the int is between 10 and 99, inclusive.
In a programming langauge, there are things called L-values and R-values. In an assignment operation, a L-value can accept a R-value as input. This comes from the typical layout which has L-values on the left of the assignment operator and R-values on the right side of the assignment operator.
x = 5;
x is the L-value and 5 is the R-value. It is possible to assign five to x.
However, a function returns a R-value. Therefore, it is possible to do this
x = a.length();
but is is not possible to do
a.length() = x;
because you can not assign a value to the return of a function.
Fundamentally, L-values are names which represent a value, but R-values are values or items which when analyzed result in the return of values.
Now, if you used the equals comparison operator, both values must be R-values, because no assignment is being performed
a.length == x
is just fine, because it is not the assignment operator = but rather one of the comparison operators ==.
Your error comes because x is a primitive, not an object. Only objects have methods like length(). A quick an easy way to determine the length of an integer is by using Math.log().
public int length(int n){
if (n == 0) return 1; // because Math.log(0) is undefined
if (n < 0) n = -n; // because Math.log() doesn't work for negative numbers
return (int)(Math.log10(n)) + 1; //+1 because Math.log10 returns one less
//than wanted. Math.log10(10) == 1.
}
This method uses the fact that the base b logarithm of an integer a is related to the length of the integer a.
Or, if you don't know how to use methods, you could do this (assuming n is the integer to check):
int length = (n == 0)? 1: ((n > 0)? (int) (Math.log(n)) + 1: (int) (Math.log(-n)) + 1);
Or, if you don't use the ternary operator, you could expand it:
int length = -1; //placeholder; might not need it.
if (n == 0) length = 1;
else if (n > 0) length = (int) (Math.log(n)) + 1;
else length = (int) (Math.log(-n)) + 1;
You can't find the length of an int by calling a method on it, but you can find the length of a String.
Try converting the int to a String and finding the length of that:
boolean isTwoDigits = x.toString().length() == 2;
You cannot call length on integer just write
if(x>=10 && x<=99)
{
//write your code here
}

Why java.Math.BigInteger bugs out after a certain limit?

Am trying to print the sum of digits in 2^n for n = 1 to 1000.
Here's what I've done.
public static void main(String[] args) {
int n = 1000;
for (int i = 1; i < n; i++) {
BigInteger power = BigInteger.valueOf((int)Math.pow(2, i));
int sum = 0;
while (power.intValue() > 0) {
sum += power.intValue() % 10;
power = power.divide(BigInteger.valueOf(10));
}
System.out.print(sum + " ");
}
}
It works only till about 2^30 or so and then prints the same result, 46, for the rest.
I tried a similar thing using "long long" in C and that printed 0's after a similar limit.
According to the answers, I changed
BigInteger power = BigInteger.valueOf((int)Math.pow(2, i));
to
BigInteger power = BigInteger.valueOf(2).pow(i);
and 46 changed to 0. Just like C.
Still not working...
You're using Math.pow to generate the value you should use the BigInteger functions to do so instead.
The sum should be stored in a BigInteger as well not an int.
You are doing integer arithmetic and then putting it into a biginteger. Use a biginteger's pow method instead.
Because you aren't using BigInteger.
Computing numbers using BigInteger doesn't let you magically store their sum in an int.
Similarly, passing an int to BigInteger.valueOf() doesn't magically make that int bigger.
You're calling Math.pow() with regular integers, not BigIntegers. You're calling it on integer literals.
You want this:
int i = 7; //or whatever power
BigInteger k = BigInteger.valueOf(2);
k = k.pow(i);

Gets last digit of a number

I need to define the last digit of a number assign this to value.
After this, return the last digit.
My snippet of code doesn't work correctly...
Code:
public int lastDigit(int number) {
String temp = Integer.toString(number);
int[] guess = new int[temp.length()];
int last = guess[temp.length() - 1];
return last;
}
Question:
How to solve this issue?
Just return (number % 10); i.e. take the modulus. This will be much faster than parsing in and out of a string.
If number can be negative then use (Math.abs(number) % 10);
Below is a simpler solution how to get the last digit from an int:
public int lastDigit(int number) { return Math.abs(number) % 10; }
Use
int lastDigit = number % 10.
Read about Modulo operator: http://en.wikipedia.org/wiki/Modulo_operation
Or, if you want to go with your String solution
String charAtLastPosition = temp.charAt(temp.length()-1);
No need to use any strings.Its over burden.
int i = 124;
int last= i%10;
System.out.println(last); //prints 4
Without using '%'.
public int lastDigit(int no){
int n1 = no / 10;
n1 = no - n1 * 10;
return n1;
}
You have just created an empty integer array. The array guess does not contain anything to my knowledge. The rest you should work out to get better.
Your array don't have initialization. So it will give default value Zero.
You can try like this also
String temp = Integer.toString(urNumber);
System.out.println(temp.charAt(temp.length()-1));
public static void main(String[] args) {
System.out.println(lastDigit(2347));
}
public static int lastDigit(int number)
{
//your code goes here.
int last = number % 10;
return last;
}
0/p:
7
Use StringUtils, in case you need string result:
String last = StringUtils.right(number.toString(), 1);
Another interesting way to do it which would also allow more than just the last number to be taken would be:
int number = 124454;
int overflow = (int)Math.floor(number/(1*10^n))*10^n;
int firstDigits = number - overflow;
//Where n is the number of numbers you wish to conserve</code>
In the above example if n was 1 then the program would return: 4
If n was 3 then the program would return 454
here is your method
public int lastDigit(int number)
{
//your code goes here.
int last =number%10;
return last;
}
Although the best way to do this is to use % if you insist on using strings this will work
public int lastDigit(int number)
{
return Integer.parseInt(String.valueOf(Integer.toString(number).charAt(Integer.toString(number).length() - 1)));
}
but I just wrote this for completeness. Do not use this code. it is just awful.

Categories

Resources