Saturday, 22 October 2016

CLRS: 2.1-4

Hey guys! I've got one of the problems from CLRS, Problem 2.1-4 for you people .
The problem demands to use array but I have used vector and list in my code in C++. But that does not make any difference to the logic, It remains same either you use array or list.

#include<iostream>
#include<vector>
#include<list>
using namespace std;

int main(){
    vector<int> v1={0,0,1};
    vector<int> v2={1,1,1};
    list<int>lst;
    cout<<"Two n bit binary number are v1 and v2"<<endl;
    int s,st,t = 0;
    for(auto i = v1.size()-1 ; i!=-1;--i){
        s = (v1[i]+v2[i] + t);
        st = (v1[i]+v2[i] + t)%2;
        if (s>1)
            t=1;
        else
            t = 0;
        lst.push_front(st);

}
    if(s>1)
        lst.push_front(1);
    for(auto &k:lst)
        cout<<k;
    return 0;
}

Did you find a cooler solution to the problem? Then what are you waiting for, Hit me hard in the comments down below. 

No comments:

Post a Comment