# Check if a given number is sparse or not

1 vote
81 views

## Problem:

I wrote a program in python to check if a given number is sparse or not. So I wrote this code:

``````def IsSparse(n):

if ((n<<1) & (n>>1)):
return 0

return 1

print(IsSparse(35))
print(IsSparse(16))
print(IsSparse(12))
print(IsSparse(72))``````

And when I run this or when I compile this it shows a wrong result. The output is:

``````1
1
1
1``````

But the actual output should be:

``````0
1
0
1``````

What should I do to get the actual result?

1 vote

## Solution:

A number is said to be a sparse number if in binary representation of the number no two or more consecutive bits are set. Write a function to check if a given number is Sparse or not.

So you can try out this code to get the actual result

``````def IsSparse(n):

if (n & (n>>1)):
return 0

return 1

print(IsSparse(35))
print(IsSparse(16))
print(IsSparse(12))
print(IsSparse(72))``````

And its output is:

``````0
1
0
1``````

Hope this should help you. If you don not understand anything please feel free to ask me any question you want to know.

Happy codng.

## Related questions

12 views
Problem: Is there any clue to solve this error: Check if a number is prime or not in C++?
32 views
7 views
Problem: Is there anyone to helo on > 'how to check if a number is even' ?
6 views
Problem: I have a problem.How can I fix this java check if character is number?
97 views
Problem: I want to know whether the character at a certain index in a string is a number or not in C++. Moreover, I wanna see whether the user entered a number as input to a character variable or some other character. How can I do that?
12 views
Problem: Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like &sup2; and &frac34; are also considered to be numeric values. then how check if a string is a number python
13 views
Problem: I will request someone to answer my question Please, I have searched on the web but I got no useful information for this, now I am in difficulty continuing my learning
1 vote