118. Convert Binary String to Integer Without strtol function or Libraries

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include <stdint.h>

/*
* 1010
* 2 * 0 + 1 = 1
* 2 * 1 + 0 = 2
* 2 * 2 + 1 = 5
* 2 * 5 + 0 = 10
*/


uint16_t binary_to_uint(const char *str) {
    // Your logic here
    uint16_t res = 0;
    while (*str) {
        res = 2 * res + (*str - '0');
        str++;
    }
    return res;
}

int main() {
    char bin[20];
    scanf("%s", bin);

    printf("%u", binary_to_uint(bin));
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote