Binary Number To Decimal Number Geeks For Geeks
Problem Link
https://practice.geeksforgeeks.org/problems/binary-number-to-decimal-number3525/1#
Solution:
1. Direct Inbuilt Function ie Integer.parseInt(String s,2(base you want to convert to))
class Solution
{
public int binary_to_decimal(String s)
{
return Integer.parseInt(s,2);
}
}
Time Complexity: Though Integer.parseInt is an inbuilt function but it has the complexity of O(String length). It is so because it reads the string character by character and converts the string into integer according to radix ie 2 here.[GFG Time: 0.3/2.0]
Space Complexity: O(1)
Auxillary Space: O(1)
Total Test Cases: 10030
Approach:
Using of inbuilt function
-----------------------------------------------------------------------------------------------------------------------------
Approach 2:
StringBuilder sb=new StringBuilder();
sb.append(s);
sb.reverse();
s=sb.toString();
int index=0;
int val=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='1'){
val=val+(int)Math.pow(2,index);
}
index++;
}
return val;
}
}
Time Complexity:O(String Length)[GFG Time:0.4/2.0]
Space Complexity: O(1)
Auxillary Space: O(1)
Total Test Cases: 10030
Approach:
Here we will traverse the string and if char is 1 then we append that value in one variable.
Why do we reverse String at the start?
The thing is if we start traversing the string without reversing it then MSB will be at a low index which will give us the wrong answer.
eg for 13 binary is 1101
if we do traversal from the start of string :
val=Math.pow(2,0)+Math.pow(2,1)+Math.pow(2,3)
val=1+2+8=11 which is wrong
while after reversal binary will be 1011
val=Math.pow(2,0)+Math.pow(2,2)+Math.pow(2,3)
val=1+4+8=13 which is correct.
So we need to reverse string as we formulate vale from LSB to MSB not vice-versa.
Thanks For Reading.😇
Share Further To Increase Knowledge Treasure.😊
Comments
Post a Comment