Can someone help me with this code? code runs properly on PC but shows wrong while submitting on Codechef?

import java.util.*;

class CielRcpt{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int[] n = new int[t];
String[] str = new String[t];
for(int i=0; i<t; i++){
n[i] = sc.nextInt();
if(n[i]%2048==0)
str[i] = Integer.toString(n[i]);
else
str[i] = Integer.toBinaryString(n[i]);
}

	for(int i=0; i<t; i++){  
		int c=0;  
		if(n[i]%2048==0)  
			System.out.println(n[i]/2048);  
		else{  
			int len = str[i].length();  
			for(int j=0; j<len; j++){  
				if(str[i].charAt(j)=='1')  
					c++;  
			}  
			System.out.println(c);  
		}  
	}  
}  

}

What are you trying to do here?-

int[] n = new int[t];
String[] str = new String[t];
for(int i=0; i<t; i++){
n[i] = sc.nextInt();
if(n[i]%2048==0)
str[i] = Integer.toString(n[i]);
else
str[i] = Integer.toBinaryString(n[i]);

Please see this proper code.
https://www.codechef.com/viewsolution/14541728

I’m converting input to String then counting number of 1’s in that Binary String. M first checking if input is divisible by 2048 because suppose if input given is 4096/6144 then according to code ans will be 1 but actually ans needed is 2

Your logic is wrong.

Let the number be P = A * 2048 + B, then the answer is A + bitcount(B), where bitcount(B) is the number of set bits in the binary representation of B.

In the case when P > 2048 but P is not divisible by 2048, you are merely the printing the bitcount§, but that can involve powers of 2 that are greater than 2048 and those are not available.

For example:-

P = 32770 
 = 16 * 2048 + 2 
 = 1000 0000 0000 0010 (in binary)

So, the answer = A + bitcount(B) = 16 + bitcount(2) = 17. But your code gives 2 which is bitcount(32770). But that involves 2^15 and that is not available to us. This is the reason that for P > 2048 we first use 2048 the maximum number of times we can and then remaining number can be made up using the power of 2’s that we have.

1 Like