Nearest smaller power of 2 for every digit of a number
Given an integer num, the task for every digit of the number is to find the highest power of 2 not exceeding that digit.
Examples:
Input: num = 4317
Output: 4214
Explanation:
The highest power of 2 ? 4 is 4.
The highest power of 2 ? 3 is 2.
The highest power of 2 ? 1 is 1.
The highest power of 2 ? 7 is 4.
Input: num = 8015
Output: 8014
Approach: Follow the steps below to solve the problem:
- Convert the number to its equivalent string.
- Traverse the string.
- If the digit is ‘0’, print 0.
- Otherwise, for every digit x, calculate 2(log2(x)).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void highestPowerOfTwo( int num)
{
string s = to_string(num);
for ( int i = 0; i < ( int )s.size();
i++) {
if (s[i] == '0' ) {
cout << "0" ;
continue ;
}
int lg = log2( int (s[i]) - 48);
int p = pow (2, lg);
cout << char (p + 48);
}
}
int main()
{
int num = 4317;
highestPowerOfTwo(num);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void highestPowerOfTwo( int num)
{
String s = Integer.toString(num);
for ( int i = 0 ; i < ( int )s.length(); i++)
{
if (s.charAt(i) == '0' )
{
System.out.print( "0" );
continue ;
}
int lg
= ( int )(Math.log(s.charAt(i) - '0' ) / Math.log( 2 ));
int p = ( int )Math.pow( 2 , lg);
System.out.print(( char )(p + 48 ));
}
}
public static void main(String args[])
{
int num = 4317 ;
highestPowerOfTwo(num);
}
}
|
Python3
import math
def highestPowerOfTwo(num) :
s = str (num)
for i in range ( len (s)):
if (s[i] = = '0' ) :
print ( "0" )
continue
lg = int (math.log2( ord (s[i]) - 48 ))
p = pow ( 2 , lg)
print ( chr (p + 48 ), end = "")
num = 4317
highestPowerOfTwo(num)
|
C#
using System;
class GFG
{
static void highestPowerOfTwo( int num)
{
String s = num.ToString();
for ( int i = 0; i < ( int )s.Length; i++)
{
if (s[i] == '0' )
{
Console.Write( "0" );
continue ;
}
int lg
= ( int )(Math.Log(s[i] - '0' ) / Math.Log(2));
int p = ( int )Math.Pow(2, lg);
Console.Write(( char )(p + 48));
}
}
public static void Main()
{
int num = 4317;
highestPowerOfTwo(num);
}
}
|
Javascript
<script>
function highestPowerOfTwo(num) {
var s = num.toString();
for ( var i = 0; i < s.length; i++) {
if (s[i] === "0" ) {
document.write( "0" );
continue ;
}
var lg = parseInt(Math.log2(s[i].charCodeAt(0) - 48));
var p = Math.pow(2, lg);
document.write(String.fromCharCode(p + 48));
}
}
var num = 4317;
highestPowerOfTwo(num);
</script>
|
Time Complexity: O(logN)
Auxiliary Space: O(1)
Last Updated :
03 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...