DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Shakeeb Shahid
Shakeeb Shahid

Posted on • Updated on

Using continue keyword to convert binary to decimal. No use of array, string or any pre-defined conversion. Complexity O(log n)

So this post is just to show a different approach to convert binary to decimal.
I would like the community to make this code better in terms of complexity. If possible 😜😝

#include<iostream>
#include<math.h>
using namespace std;
int main()
{

    int n;
    cin >> n;
    int count=0;
    int sum =0;
    for(int i=n;i>0;i=i/10)
    {
       int rem = i%10;
        if(rem==0)
        {
            count =count +1;
            continue;
        }
        else if(rem==1)
        sum = sum + pow(2,count);
        count =count+1;
    }
    cout << sum <<endl;
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity : O(log n)
Correct me guys if I'm wrong!
Thanks.....

Top comments (0)

Create an Account!

πŸ‘€ Just want to lurk?

That's fine, you can still create an account and turn on features like 🌚 dark mode.