Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2014
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. struct BigInt
  2. {
  3.     bool negative;
  4.     vector<char> digits;
  5. }
  6.  
  7. BigInt substract(BigInt& a, BigInt& b)
  8. {
  9.     BigInt result;
  10.     if(a.negative!=b.negative){
  11.         result.negative=a.negative;
  12.         result.digits=unsignedAdd(a.digits, b.digits);
  13.         return result;
  14.     } else {
  15.         if(gt(a.digits, b.digits)){
  16.             result.digits=unsignedSub(a.digits, b.digits);
  17.             result.negative=a.negative;
  18.             return result;
  19.         } else{
  20.             result.digits=unsignedSub(b.digits, a.digits);
  21.             result.negative=!a.negative;
  22.             return result;
  23.         }
  24.     }
  25.     return result;
  26. }
  27.  
  28. bool gt(vector<char>& a, vector<char>& b)
  29. {
  30.     int lena=a.size();
  31.     int lenb=b.size();
  32.     if(lena>lenb){
  33.         return true;
  34.     } else if(lena<lenb){
  35.         return false;
  36.     }
  37.  
  38.     for(int i=lena-1;i>=0;i++){
  39.         if(a[i] & 0xF0 > b[i] & 0xF0){
  40.             return true;
  41.         }else if(a[i] & 0xF0 < b[i] & 0xF0){
  42.             return false;
  43.         }
  44.  
  45.         if(a[i] & 0x0F > b[i] & 0x0F){
  46.             return true;
  47.         }else if(a[i] & 0x0F < b[i] & 0x0F){
  48.             return false;
  49.         }
  50.     }
  51.     return false;
  52. }
  53.  
  54. vector<char> unsignedSub(vector<char>& a, vector<char>& b)
  55. {
  56.     // assume a>=b
  57.     int lena=a.size();
  58.     int lenb=b.size();
  59.     vector<char> result;
  60.  
  61.     int flag=0;
  62.     for(int i=0;i<lenb;i++){
  63.         int low=a[i]&0x0F-b[i]&0x0F+flag;
  64.         if(low < 0){
  65.             low+=10
  66.             flag=-1;
  67.         }
  68.  
  69.         int high=(a[i]>>4)&0xF0-(b[i]>>4)&0xF0+flag;
  70.         if(high<0){
  71.             high+=10
  72.             flag=-1;
  73.         }
  74.         result[i]=high<<4 | low;
  75.     }
  76.     for(;i<lena;i++){
  77.         int low=a[i]&0x0F+flag;
  78.         if(low < 0){
  79.             digit +=10
  80.             flag=-1;
  81.         }
  82.  
  83.         int high=(a[i]>>4)&0xF0+flag;
  84.         if(high<0){
  85.             high+=10
  86.             flag=-1;
  87.         }
  88.         result[i]=high<<4 | low;
  89.     }
  90.     return result;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement