Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Sunday, October 1, 2017

Consecutive Sum of number


Check if a number can be expressed as consecutive sum of two or more numbers.

Idea is that the number who are in 2^n can't be expressed rest can be

Code:

 public static boolean consecutivesum(long n)
     {
         return ((n&(n-1))!=0 && n!=0);
     }
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
    long n=ab.nextLong();
    System.out.println(consecutivesum(n)?"1":"0");
}
}

0 Comments:

Post a Comment

Stats