For understanding the binary conversion of and click here to
Explaination:
In the problem statement the given string of arr we need to convert decimal to binary and save in same format year/month/date like that in there we need convert decimal to binary but there given string we can't basic logic of Decimal to binary conversion its very difficultly for converting string values to integer value. In that time we use "stoi" keyword for converting string to integer but it not flexible for large values similar we perform conversion to integer by ASCII values, mostly this is used in some programming language let take example:
Let take x="25"; here x is the string we convert each individual values to integer it's not done entire once so like then x has size of 2 for i=1 (iteration) we come reverse order it's we simply subtraction of the '0' ASCII value of zero this will convert string to integer for that one element then "5" to 5 like this int kl=x[1]-'0'; that Value is stored in kl integer then we convert to binary by basic logic to understand the basic logic of Decimal to binary click here we cover the how we convert the string to integer let come to problem here some common point we need to discuss when date it has two numbers max right like this d="09",d="24" maximum d="31"; when it comes to month also same m="12"; when it's come to year it has 4 numbers y="2002"; so let take index values to clear understanding of how we apply the logic:S
String arr= 0 1 2 3 4 5 6 7 8 9
String arr="2 0 8 0 - 0 2 - 2 9"
In here at index 4,7 has - it's common for each input by experts that numbers we convert each date and month and year to integers int d=((arr[8]-'0')*10)+arr[9]-'0'; here also date,month,year common for every input
int y=((arr[0]-'0')*1000+(arr[1]-'0')*100+(arr[2]-'0')*10+(arr[3]-'0')*1);
We manual convert date first by convert of each value it has also change to integer to string by adding ASCII value of '0' after complete the date we add to ' - ' answer string before the month operation month also has same operation like date at year also do like this after all the operation was completed we return the answer string but its get wrong because we do all operation in reverse so we need to reverse the answer of the string and return answer string or (nums I will take )
CODE:
class Solution { public: string convertDateToBinary(string arr) { /*index 0 1 2 3 4 5 6 7 8 9 string = "2 0 8 0 - 0 2 - 2 9" year month date */ int d=(arr[8]-'0')*10+(arr[9]-'0');
int m=(arr[5]-'0')*10+(arr[6]-'0');
int y=(arr[0]-'0')*1000+(arr[1]-'0')*100
+(arr[2]-'0')*10+(arr[3]-'0');
// O(3n)=>O(n) string str=""; while(d>0){ str+=(d%2+'0'); d=d/2; } str+='-'; while(m>0){ str+=(m%2+'0'); m=m/2; } str+='-'; while(y>0){ str+=(y%2+'0'); y=y/2; } reverse(str.begin(),str.end()); return str; } };
When you understand this problem how to solve try to solve by click here
the code is submitted in 0ms
Post your solutions in the comments below!
0 Comments