Write a program to convert a decimal number into a hexadecimal number.
Example 1:
Input:56
Output:38
Example 2:
Input:168
Output:A8
Approach:
Java
public class DecimalToHexadecimal {public static void main(String[] args) {int decimal = 168;String hexadecimal = decimalToHexadecimall(decimal);System.out.println("Hexadecimal is " + hexadecimal);}public static String decimalToHexadecimall(int decimal) {String hexa = "";while (decimal > 0) {// calculate mode on base 16int mode = decimal % 16;if (mode < 10) {hexa = mode + hexa;} else {// 56+10='A', 56+11=Bhexa = (char) (56 + (mode - 1)) + "" + hexa;}decimal = decimal / 16;}return hexa;}}
C++
#include <bits/stdc++.h>using namespace std;//Function to convert from//decimal to hexadecimalstring decimalTohexaDecimal(int num){string hexaDecimal="";while(num>0){int mod=num%16;if(mod<=9)hexaDecimal+=to_string(mod);elsehexaDecimal+='A'+mod-10;num=num/16;}reverse(hexaDecimal.begin(),hexaDecimal.end());return hexaDecimal;}int main(){int num=168;string hexaDecimal=decimalTohexaDecimal(num);cout<<"Hexadecimal is ";cout<<hexaDecimal<<"\n";return 0;}
No comments:
Post a Comment