华为往年笔试题【十六进制转十进制字符串】

题目:写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。(多组同时输入 )

 1 #include<iostream>
 2 //#include<cstring>
 3 #include<string>
 4 #include<math.h>
 5 #include<vector>
 6 //#include<stdio.h>
 7 using namespace std;
 8 
 9 int main(){
10         string str;
11         vector<int> result;
12         while(cin >> str){
13                 int sum = 0;
14                 //cout << "this" ;
15                 for(int i = 2 ; i < str.size() ; i++){
16                         int temp = str[i] - '0';
17                         if(temp > 10){
18                                 temp = str[i] - 'A' + 10;
19                         }
20                         sum = sum + temp * pow(16,str.size() - i - 1);
21 //                      cout <<pow(16,str.size() - i - 1) << endl;
22 //                      cout << sum <<endl;
23                 }
24                 result.push_back(sum);
25         }
26         for(vector<int> :: iterator it = result.begin();it != result.end();it ++)
27         {
28                 cout << *it << endl;
29         }
30         return 0 ;
31 }

大神做法:

链接:https://www.nowcoder.com/questionTerminal/8f3df50d2b9043208c5eed283d1d4da6
来源:牛客网

#include <iostream>
using namespace std;

int main()
{
    int a;
    while(cin>>hex>>a){
    cout<<a<<endl;
    }
}

在C++中,dec指示cout以十进制输出,hex指示cout以十六进制输出,oct指示cout以八进制输出,它们的头文件是#include<iostream>

而如果想指示cout以二进制输出,则要用bitset<num>,bitset表示二进制输出,num表示位数,它的头文件是#include<bitset>

 1 #include <iostream>
 2 #include <bitset>
 3  
 4 using namespace std;
 5  
 6 int main()
 7 {
 8     int a=64;
 9     cout<<(bitset<32>)a<<endl;//二进制32位输出
10     cout<<oct<<a<<endl;
11     cout<<dec<<a<<endl;
12     cout<<hex<<a<<endl;
13     return 0;
14 }

C++ 输入输出八进制、十进制、十六进制

 https://www.cnblogs.com/zhuobo/p/10254571.html

原文地址:https://www.cnblogs.com/lijiaxin/p/10658111.html