Find position of the given number among the numbers made of 4 and 7
Last Updated :
06 Jan, 2024
Consider a series of numbers composed of only digits 4 and 7. The first few numbers in the series are 4, 7, 44, 47, 74, 77, 444, .. etc. Given a number constructed by 4, 7 digits only, we need to find the position of this number in this series.
Examples:
Input : 7
Output : pos = 2
Input : 444
Output : pos = 7
It is reverse of the following article :
Find n-th element in a series with only 2 digits (4 and 7) allowed | Set 2 (log(n) method)
""
/ \
1(4) 2(7)
/ \ / \
3(44) 4(47) 5(74) 6(77)
/ \ / \ / \ / \
The idea is based on the fact that all even positioned numbers have 7 as the last digit and all odd positioned numbers have 4 as the last digit.
If the number is 4 then it is the left node of the tree, then it corresponds to (pos*2)+1. Else right child node(7) corresponds to (pos*2)+2.
Implementation:
C++
Java
Python3
C#
PHP
<?php
function findpos( $n )
{
$i = 0;
$pos = 0;
while ( $i < strlen ( $n )) {
switch ( $n [ $i ])
{
case '4' :
$pos = $pos * 2 + 1;
break ;
case '7' :
$pos = $pos * 2 + 2;
break ;
}
$i ++;
}
return $pos ;
}
$n = "774" ;
echo findpos( $n );
?>
|
Javascript
<script>
function findpos(n)
{
let i = 0;
let pos = 0;
while (i < n.length) {
switch (n[i])
{
case '4' :
pos = pos * 2 + 1;
break ;
case '7' :
pos = pos * 2 + 2;
break ;
}
i++;
}
return pos;
}
let n = "774" ;
document.write(findpos(n));
</script>
|
Time Complexity: O(n), where n represents the size of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Share your thoughts in the comments
Please Login to comment...