题解 | #进制转换#

进制转换

http://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6

解题思路:

  1. 判断s这个字符串每个位置上的值
  2. 如果这个值是A-F用另外一个int 数组来保存对应的数字
  3. 0X 代表是十六进制的数字,所以数组下标从2开始
  4. 由于16进制最后一位是0次方,所以pow函数是pow(16,s.leng()-i-1)
  5. 由于在字符串中的数字取出来是字符型,所以要进行对应的转化,在1-9之间之间减去第'0'个字符就得到了对应的整数
  6. #include <bits/stdc++.h>
    using namespace std;
    int  temp[10005];
    int main(){
        string s;
        cin>>s;
        int num=0;
        char m;
        for(int i=2;i<s.length();i++){
            if(s[i]=='A'){
               temp[i]=10;
               num+=temp[i]*pow(16,s.length()-i-1);
            }
             else if(s[i]=='B'){
                temp[i]=11;
                num+=temp[i]*pow(16,s.length()-i-1);
            }
            else if(s[i]=='C'){
               temp[i]=12;
               num+=temp[i]*pow(16,s.length()-i-1);
                
            }
            else if(s[i]=='D'){
                temp[i]=13;
                num+=temp[i]*pow(16,s.length()-i-1);
            }
             else if(s[i]=='E'){
                temp[i]=14;
                num+=temp[i]*pow(16,s.length()-i-1);
            }
              else if(s[i]=='F'){
                temp[i]=15;
                num+=temp[i]*pow(16,s.length()-i-1);
            }else if(s[i]>'0'&&s[i]<='9') {
                  s[i]=s[i]-'0';
                   num+=s[i]*pow(16,s.length()-i-1);
              }
            
        }
        cout<<num;
        return 0;
    }

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务