I've been trying to write a small and simple program that converts dec numbers to bin.The idea is that when the user enters a positive integer a for- cycle have to go through all the rounds of deviding the number /2 but it also have to get the tail (idk the math term really the actuall bin numbers) and write them in an array, thats the part Im having trouble with.I have predefined the array size of 30 (cant find a way to make a working array without specifying it's length) my idea was that then I could make a reversed array with length = index(i from the first for cycle) from the previous array with another for cycle etc. but when I tested the first array all I get is empty brackets printed: [] or nothing at all, eclipse doesnt find any errors in the code and I cant figure out whats wrong.I could use some help.Anyways here's the code:
public static void decToBin(){
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer:");
n = in.nextInt();
in.close();
if (n <= 0) {System.out.println("ERROR:n<=0");return;}
else if (n > 0){
int[] ostataci = new int[30];
for (int i = 0;n <= 0;i++){
ostataci[i] = n % 2;
n = n / 2;
// System.out.printf("%d %n", ostataci[i]); - even this one doesnt print at all
}
// System.out.println(Arrays.toString(ostataci)); - nor this one
}
}
Thanks for the replies Ive learnt a few new things.But since Im a newbie I wanted to do it with the metod I described thx for pointing me the error in the for cycle, that was my biggest problem, anyway heres the last code I wrote( working correctly) thats what I was trying to do from the beggining.
public static void decToBin2(){
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer:");
n = in.nextInt();
in.close();
int i = 0;
int[] ostataci = new int[32];
if (n <= 0) {System.out.println("ERROR:n<=0");return;}
else if (n > 0){
while (n > 0){
i++;
ostataci[i] = n % 2;
n = n / 2;
}
}
int reverse = i;
int[] reversed = new int[reverse];
for (int i2 = 0;i2 != reverse;i--,i2++){
reversed[i2] = ostataci[i];
System.out.print(reversed[i2]);
}
}
The immediate error is in the for loop:
else if (n > 0) {
// Since n > 0 it'll never run
for (int i = 0;n <= 0;i++)
The implementation itself could be something like that (keep it simpler!):
...
if (n <= 0)
System.out.println("ERROR:n<=0");
else {
// Why do we need array/ArrayList etc.? We are supposed to build a string!
StringBuilder Sb = new StringBuilder();
// while we have something to do...
// (are we supposed to compute exact number of steps? No)
while (n > 0) {
Sb.insert(0, n % 2);
n /= 2;
}
System.out.println(Sb.toString());
}
Your loop for (int i = 0;n <= 0;i++){ } won't execute because you know that n is positive (by your if condition), but the for condition demands that n be negative (n <= 0). I suspect you mean n>0 instead.
As for variable length arrays you can use Lists, although that might be better to add in later
your for loop is wrong for (int i = 0;n <= 0;i++){ this just wont run change it to something like this while (n > 0) { and your code will works fine. also int is 32 bit so change int[] ostataci = new int[30]; to int[] ostataci = new int[32]; although it is better to uselist instead of array.
Decimals are already converted to binary on the computer, why don't you use bit wise operations to check the saved integer? Eg to check if bit n of an int is set, evaluate the boolean (number >> n) & 1. Just put that in a loop and you're done. Everyone else is making it too complicated.
Here is an alternative approach, using the shift operator and bit-masking:
public static int[] dec2bin(int n) {
int[] result = new int[32];
for (int i = 0; i < 32; i++) {
result[31-i] = n & 0x1;
n >>= 1;
}
return result;
}
This will also work just fine for negative numbers.
Example usage:
public static void main(String[] args) {
int[] result = dec2bin(5);
for (int i : result)
System.out.print(i);
System.out.flush();
}
Ouput:
00000000000000000000000000000101
Explaination
The code n & 0x1 from above is bit-masking. The 0x1 is hex notation for the number 1. In binary, that number looks like this:
00000001
In the first iteration of the for loop, n looks like:
00000101
The & operator does a bit-by-bit (bitwise) comparison of the bits in the two numbers, 'anding' them together, producing a new number based on those comparisons. If either or both of the corresponding bits are 0, the resulting bit is 0. If both of them are 1, the resulting bit is 1. So, for the two numbers listed above, the result of 'anding' them together is:
00000001
Or, in decimal, 1. You'll note that that also happens to be the bit value of the rightmost bit in n. Which we save into the result array at the rightmost index.
Next, we shift (>>) n right by 1. This moves every bit along by one (the rightmost bit is lost), and the resulting n is now:
00000010
We repeat that process 32 times (for each of the 32 bits of an int) and at the end we get a result array containing the correct answer.
Try this:
package mypackage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Arrays;
public class Converter{
final static int ARRAY_SIZE = 30;
public static void main(String[] args){
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer:");
n = in.nextInt();
in.close();
if (n <= 0){
System.out.println("ERROR:n<=0");
return;
}else if (n > 0){
int[] ostataci = new int[ARRAY_SIZE];
int i = 0;
while (n>0){
ostataci[i] = n % 2;
i++;
n = n / 2;
System.out.printf("%d %n", ostataci[i]);
}
System.out.println("All done!");
System.out.println(Arrays.toString(ostataci));
}
}
}
Related
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0) {
int n=sc.nextInt();
while(true) {
boolean ok = true;
int num = n;
while(num > 0) {
if(ok && num % 3 == 2)
ok = false;
num = num / 3;
}
if (ok)
break;
++n;
}
System.out.println(n);
}
How can I optimize my code? This code is calculating an integer that can be represented as a sum of distinct powers of 3.
Your code runs in $O(N \log N)$. I think you are trying to solve this question from CodeForces. You have not mentioned the limits on $n$, but the question says that $n$ can be as large as $10^18$, an $O(N \log N)$ solution shall simply fail. Moreover, the question mentions there may be 500 queries, you need to solve the query 500 times within the time limit.
Note that, you receive "time limit exceeded" on those competitive programming sites, whenever the time is exceeded. It does not mean that your code executes in 1.01 seconds and you miss the limit by only 0.01 seconds. It just means that your code failed to execute in 1 second and stopped in 1.01 seconds. You cannot understand how long your code would take if it is allowed to run. You can do those checks on your own machine.
Having said all those, hint for the solution of the question:
Observation: Any number $n$ cannot be expressed as a sum of distinct powers of 3 if its base-3 representation contains "2".
Then, the question simply asks for the smallest integer greater than or equal to n and does not contain a "2" in its base-3 representation.
Consider the most significant "2" digit in the base-3 representation of the number. Take the digits before that "2". Count the number of digits "remaining" including the "2". Assume that number is in base-2, and add "1". Add "remaining" number of trailing zero digits to the number. Convert that "base-3" number to base-10 and output the result.
This algorithm runs in $O(log N)$, which should be sufficient to get an "Answer Correct".
A solution utilizing Java BigInteger is as follows:
void solve(long n) {
final char[] chars = BigInteger.valueOf(n).toString(3).toCharArray();
final int twoDigit = getTwoDigit(chars);
if (twoDigit == -1) {
System.out.println(n);
} else {
int remaining = chars.length - twoDigit;
final BigInteger a;
if (twoDigit == 0) {
a = BigInteger.ONE;
} else {
a = new BigInteger(new String(chars, 0, twoDigit), 2).add(BigInteger.ONE);
}
BigInteger b = new BigInteger(a.toString(2), 3);
BigInteger result = b.multiply(BigInteger.valueOf(3).pow(remaining));
System.out.println(result);
}
}
private static int getTwoDigit(char[] chars) {
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '2') {
return i;
}
}
return -1;
}
I am trying to practice java over the summer and i'm stuck on this problem. I need to swap the 2 letters in a integer in java. For example in my main method I make a method called swapdigits and have my parameters as 1432. The program should swap the 4 and 1 and 3 and 2. The output should be 4123 since it swapped the two letters in order. Lets say I do swapdigits(1341234) the output should be 3114324. I know I have to use while loops but i'm getting stuck on the swapping.
This is what I have so far:
public static void main(String[] args) {
Swapdigits(2413);
}
public static void Swapdigits(int number){
while(number>0){
int y=number/1000;
int x=number%10;
int original=number-y;
System.out.println(original);
}
System.out.println();
}
}
public static int swapDigitPairs(int number) {
int result = 0;
int place = 1;
while (number > 9) {
result += place * 10 * (number % 10);
number /= 10;
result += place * (number % 10);
number /= 10;
place *= 100;
}
return result + place * number;
}
You can also try
char[] a = String.valueOf(number).toCharArray();
for (int i = 0; i < a.length - 1; i += 2) {
char tmp = a[i];
a[i] = a[i + 1];
a[i + 1] = tmp;
}
int number = Integer.parseInt(new String(a));
Because you're just swapping the places of digits, it doesn't actually matter what the number is. So, it's probably easier (and makes more sense) to represent the argument as a string. That way you aren't dealing with weird modulo operators - If you were solving the problem by hand, would you actually do any math? You'd treat this problem the same whether it were numbers of a bunch of characters.
Take a look at the following question for information on swapping characters in a String:
How to swap String characters in Java?
I have to create a java program that converts binary to decimal using the following steps. Being new at this I did something, but I don't know what I did wrong or how to continue.
public class BinaryToDecimal {
public static void main(String args[]){
long sum = 0;
int result;
String s = "1001010101011010111001011101010101010101";
for(int i = s.length()-1; i <= 0; i--){
result = (int)Math.pow(2, i);
if(s.charAt(i) == '1')
sum=sum + result;
}
System.out.println(sum);
}
}
Use a loop to read (charAt()) each digit (0/1 char) in the input string, scanning from right to left;
Use the loop to build the required powers of 2;
Use a conditional statement to deal with 0 and 1 separately;
Debug using simple input, e.g. 1, 10, 101, and print intermediate values in the loop.
Use your program to find the decimal value of the following binary number:
1001010101011010111001011101010101010101
Do this only if your decimal value is at most 2147483647 or the maximum value an int can be in Java. If you don't know, just check the length of your string. If it's less than or equal to 32 i.e. 4 bytes, then you can use parseInt.:
int decimalValue = Integer.parseInt(s, 2);
Refer HERE for more info on the Integer.parseInt();
But if it's more, you can use your code. I modified your loop which is where your problem was:
String s = "1001010101011010111001011101010101010101";
long result = 0;
for(int i = 0; i < s.length(); i++){
result = (long) (result + (s.charAt(i)-'0' )* Math.pow(2, s.length()-i-1));
}
System.out.println(result);
The first thing I notice is that your binary number has more than 32 bits. This cannot be represented in the space of an int, and will result in overflow.
As a simpler answer, I ran the following and got the correct value at the end, it just uses simple bit shifts.
For each index in the string, if the character is 1, it sets the corresponding bit in the result.
public class BinaryToDecimal {
public static void main(String[] args) {
long sum;
String bin = "1001010101011010111001011101010101010101";
sum = 0;
for (int i = 0; i < bin.length(); i++) {
char a = bin.charAt(i);
if (a == '1') {
sum |= 0x01;
}
sum <<= 1;
}
sum >>= 1;
System.out.println(sum);
}
}
The loop runs from i = s.length()-1 until i <= 0. This should be i>=0.
The next problem is "int result". It works fine with result as a long ;) (Reason: You calculate a 40-bit value at the MostSignificantBit, but Integers only use 32-bit)
Also: You start at the rightmost Bit with i=s.length()-1. But the power that you calculate for it is 2^(s.length()-1) though it should be 2^0=1.
The solution is: result = (long)Math.pow(2, s.length()-1-i)
Edit:
I really like the solution of user2316981 because of its clear structure (without Math.pow, should be faster by using shift instead). And loops from 0 to MSB as I do with Double&Add algorithm. Can't comment on it yet, but thanks for the reminder ;)
import java.util.*;
import java.lang.Math;
class deci {
int convert(int n) {
int tem=1,power=0;
int decimal=0;
for (int j=0;j<n;j++) {
if(n==0) {
break;
} else {
while(n>0) {
tem=n%10;
decimal+=(tem*(Math.pow(2,power)));
n=n/10;
power++;
}
}
}
return decimal;
}
public static void main(String args[]) {
System.out.print("enter the binary no");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
deci dc=new deci();
int i=dc.convert(n);
System.out.print(i);
}
}
I'm working on a practice program at InterviewStreet and I have a solution that runs with a time of 5.15xx seconds, while the maximum time allowed for a java solution is 5 seconds. Is there anything I can do with what I've got here to get it under 5 seconds? There's also a limit of 256 MB so as near as I can tell this is both the most time and memory efficient solution to the problem...
edit:
The possible values for N and K are N <= 10^9 and K <= N, which is why I chose to do everything using BigInteger. The maximum number of trials is 10000. So basically, you input the number of trials, then a pair of integer values for each number of trials, and the program computes the three versions of the binomial coefficient for the equation in the second loop. I figured it would be faster to read everything into the arrays, then process the arrays and put the results into a third array to be processed by the third loop because I figured it might be faster that way. I tried doing everything in the same loop and it ran slower.
I've tried three or four different algorithms for calculating the binomial coefficient (nCr - or n choose r, all are different ways of saying the same thing). Some of the algorithms involve a two dimensional array like c[n][k]. This is the only solution I've submitted that didn't come back with some sort of memory error. The answer needs to be output mod (10 ^ 6) + 3 because the answers of nCr * nCr get pretty huge. A sample run of the program is:
3
4 1
5 2
90 13
2
5
815483
Can't run it on a faster machine because it needs to pass on their machine to count, basically I submit the code and they run it against their test cases, and I have no idea what their test case is, just that the inputs are within the bounds given above.
And the program itself:
import java.math.BigInteger;
import java.util.Scanner;
public class Solution {
public BigInteger nCr(int n, int r) {
if (r > n ) {
return BigInteger.ZERO;
}
if (r > n / 2) {
r = n - r;
}
BigInteger result = BigInteger.ONE;
for (int i = 0; i < r; i++) {
result = result.multiply(BigInteger.valueOf(n - i));
result = result.divide(BigInteger.valueOf(i + 1));
}
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
BigInteger m = BigInteger.valueOf(1000003);
Solution p = new Solution();
short T = input.nextShort(); // Number of trials
BigInteger intermediate = BigInteger.ONE;
int[] r = new int[T];
int[] N = new int[T];
int[] K = new int[T];
short x = 0;
while (x < T) {
N[x] = input.nextInt();
K[x] = input.nextInt();
x++;
}
x = 0;
while (x < T) {
if (N[x] >= 3) {
r[x] = ((p.nCr(N[x] - 3, K[x]).multiply(p.nCr(N[x] + K[x], N[x] - 1))).divide(BigInteger.valueOf((N[x] + K[x]))).mod(m)).intValue();
} else {
r[x] = 0;
}
x++;
}
x = 0;
while (x < T) {
System.out.println(r[x]);
x++;
}
}
}
Not entirely sure what the algorithm is trying to accomplish but I'm guessing something with binomial coefficients based on your tagging of the post.
You'll need to check if my suggestion modifies the result but it looks like you could merge two of your while loops:
Original:
while (x < T) {
N[x] = input.nextInt();
K[x] = input.nextInt();
x++;
}
x = 0;
while (x < T) {
if (N[x] >= 3) {
r[x] = ((p.nCr(N[x] - 3, K[x]).multiply(p.nCr(N[x] + K[x], N[x] - 1))).divide(BigInteger.valueOf((N[x] + K[x]))).mod(m)).intValue();
} else {
r[x] = 0;
}
x++;
}
New:
x = 0;
while (x < T) {
//this has been moved from your first while loop
N[x] = input.nextInt();
K[x] = input.nextInt();
if (N[x] >= 3) {
r[x] = ((p.nCr(N[x] - 3, K[x]).multiply(p.nCr(N[x] + K[x], N[x] - 1))).divide(BigInteger.valueOf((N[x] + K[x]))).mod(m)).intValue();
} else {
r[x] = 0;
}
x++;
}
try to run using a profilerm for example the jvisualvm and run this class with
-Dcom.sun.management.jmxremote
attach to the process and start a profile.
I want to convert decimal numbers to binary numbers. I want to store them in an array.
First I need to create an array that has a certain length so that I can store the binary numbers. After that I perform the conversion, here is how I do it:
public class Aufg3 {
public static void main(String[] args) {
int[] test = decToBin(12, getBinArray(12));
for(int i = 0; i < test.length; i++){
System.out.println(test[i]);
}
}
public static int[] getBinArray(int number){
int res = number, length = 0;
while(res != 0){
res /= 2;
length++;
}
return new int[length];
}
public static int[] decToBin(int number, int[] array){
int res = number, k = array.length-1;
while(res != 0){
if(res%2 == 0){
array[k] = 0;
}else{
array[k] = 1;
}
k--;
res /= 2;
}
return array;
}
}
Is there anything to improve? It should print 1100 for input of 12.
Why not just use the toBinaryString method of the Integer class:
System.out.println(Integer.toBinaryString(12))
I assume you want to write your own code -- otherwise this is straightforward to do using methods from the standard Java library.
Some quick comments:
You can get rid of the res temp vars. Work directly on number (remember that Java passes parameters by value).
Shift is more efficient than division (number >>>= 1 instead of number /= 2), although the compiler should be able to optimize this anyway
You can avoid the modulus in decToBin if you just do array[k] = number & 1;
While you are at it, why not call getBinArray from decToBin directly? Then you can call decToBin with only one arg -- the value to convert.
Here is a slightly optimized version of your code:
public static int[] getBinArray(int number) {
int length = 0;
while (number != 0) {
number >>>= 1;
length++;
}
return new int[length];
}
public static int[] decToBin(int number) {
int[] array = getBinArray(number);
int k = array.length-1;
while (number != 0)
{
array[k--] = number & 1;
number >>>= 1;
}
return array;
}
If this isn't homework, no need to do it yourself. The following code should work:
BigInteger bigInt = new BigInteger(number);
String asString = bigInt.toString(2);
There might be more efficient ways, but this is certainly very readable and maintainable.
There are some small things that you can improve:
You should define a "high-level" method that converts an int to an int[]. In the current code you have to mention the 12 two times, which is bad.
You should use a do { ... } while (number != 0) loop. Otherwise the number 0 will be represented by an empty array.
You should use x >>> 1 instead of x / 2, since that handles negative numbers correctly.
If you want to check that your code is correct, write another method that converts back from binary to int. Then you can check that binToDec(decToBin(12, ...)) == 12.
The method getBinArray should not be public, since it is only a helper method. You can either replace the public with private or just remove the public.