# 【原】 POJ 3748 位操作 解题报告

http://poj.org/problem?id=3748

Description

Input

Output

Sample Input

12345678,0,3

Sample Output

1234567c

   1: #include <iostream>
   2: #include <fstream>
   3: #include <string>
   4:
   5: using namespace std ;
   6:
   7: //A~F : 10~15
   8: int alpArrUp[6]={10,11,12,13,14,15} ;
   9: //a~f : 10~15
  10: int alpArrLow[6]={10,11,12,13,14,15} ;
  11:
  12: void run3748()
  13: {
  14:     ifstream in("in.txt") ;
  15:
  16:     string str ;
  17:     string numStr,xStr,yStr ;
  18:     string num16 ;
  19:     unsigned num,x,y,tmp1,tmp0,tmpnum ;
  20:     string::size_type pos1,pos2 ;
  21:     int i,j ;
  22:     int len ;
  23:
  24:     in>>str ;
  25:     pos1 = str.find_first_of(',') ;
  26:     pos2 = str.find_last_of(',') ;
  27:
  28:     //从字符串中取得待置位的数、x、y
  29:     numStr = str.substr(0,pos1) ;
  30:     xStr = str.substr(pos1+1,pos2-pos1-1);
  31:     yStr = str.substr(pos2+1);
  32:
  33:     //将字符串转化成16进制数
  34:     //需要注意字符串的0位在左，数字的0位在右，转换时容易出错
  35:     num = 0 ;
  36:     len = numStr.size() ;
  37:     for( i=len-1,j=0 ; i>=0 ; --i,++j )
  38:     {
  39:         if( numStr[i]>='a' && numStr[i]<='f' )
  40:             num += ( alpArrLow[numStr[i]-'a']<<(4*j) ) ;
  41:         else if( numStr[i]>='A' && numStr[i]<='F' )
  42:             num += ( alpArrUp[numStr[i]-'a']<<(4*j) ) ;
  43:         else
  44:             num += ( (numStr[i]-'0')<<(4*j) ) ;
  45:     }
  46:
  47:     //将x转成数字
  48:     len = xStr.size();
  49:     if(len==1)
  50:         x = xStr[0]-'0' ;
  51:     else if(len==2)
  52:         x = (xStr[1]-'0')+(xStr[0]-'0')*10 ;
  53:
  54:     //将y转成数字
  55:     len = yStr.size();
  56:     if(len==1)
  57:         y = yStr[0]-'0' ;
  58:     else if(len==2)
  59:         y = (yStr[1]-'0')+(yStr[0]-'0')*10 ;
  60:
  61:     //置位
  62:     tmp1 = 0xffffffff ;
  63:     tmp0 = 0x00000000 ;
  64:
  65:     //对第x位置0
  66:     //即将num的第x位“与”0，在做“与”时若保证其他位不变，则需要“与”1
  67:     num &= (tmp1 ^ (1<<x) ) ;
  68:
  69:     //对第y、y-1位置1
  70:     num |= (tmp0 ^ (3<<(y-1)) ) ;
  71:     //对第y-2位置0
  72:     num &= (tmp1 ^ (1<<(y-2)) ) ;
  73:
  74:     //输出16进制表示用std::hex
  75:     cout<<std::hex<<num<<endl;
  76: }
posted @ 2010-11-09 20:01  Allen Sun  阅读(494)  评论(0编辑  收藏  举报