#error in the code

17 messages · Page 1 of 1 (latest)

sour light
#

the code below should return true for input n=10 and k =3 but it is giving false,

it's as if while execution it is ignoring if part,it is getting executed if I comment the else part

class CheckBit
{
// Function to check if Kth bit is set or not.
static boolean checkKthBit(int n, int k)
{
// Your code here
boolean a;
String bina=Integer.toBinaryString(n);
char aa=bina.charAt(k);
if(aa==1){
a=true;
}
else {
a=false;
}
return a;

}

}

uncut zodiacBOT
#

This post has been reserved for your question.

Hey @sour light! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

uncut zodiacBOT
sharp mauve
#

you are comparing a char to an integer. Compare a char to a char

sour light
#

but chat gpt said In Java, you can compare two char values using the equality operator (==).

sharp mauve
#

yeah but one is not a char.
this is a char'1'
this is an integer1

#

look at this line closely: if(aa==1){

umbral edgeBOT
#

i updated it to char aa=bina.charAt(k);
char a1='1'; if(aa==a1){ a=true; } but it is stall not working

This message has been formatted automatically. You can disable this using /preferences.

sharp mauve
#

the first bit is the one to the very right:
3 in binary is 11
the first bit is the rightmost 1.

sour light
#

n=10 and k =3

#

it's checkinig for 10 not 3

sharp mauve
#
10 in binary is: 1010
Your current implementation returns the red 0. By my understanding it should return the blue 1.
sour light
#

that's what I am asking why is it returning 0 instead of 1

sharp mauve
#

because you are looking at it from the wrong side. The red 0 is the first bit, not the blue 1.

sour light
#

thank you got it

uncut zodiacBOT
# sour light thank you got it

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.