Xisepe

sub in different bases

May 2nd, 2022
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.81 KB | None | 0 0
  1. int subInBase(const int base, const int first, const int second) {
  2.     if (base < 1 || base > 10) {
  3.         puts("bad base");
  4.         return INT_MAX;
  5.     }
  6.     char sgn = 1;
  7.     int cp_first, cp_second;
  8.     int result = 0;
  9.     if (first >= second) {
  10.         cp_first = first;
  11.         cp_second = second;
  12.     } else {
  13.         cp_first = second;
  14.         cp_second = first;
  15.         sgn = -1;
  16.     }
  17.     int carry = 0;
  18.     int k = 1;
  19.     while (cp_first > 0) {
  20.         int sub = cp_first % 10 - cp_second % 10;
  21.         if (sub < 0) {
  22.             result += (sub + base) * k;
  23.             carry = 1;
  24.         } else {
  25.             result += sub * k;
  26.             carry = 0;
  27.         }
  28.         k *= 10;
  29.         cp_first /= 10;
  30.         cp_first -= carry;
  31.         cp_second /= 10;
  32.     }
  33.     return result * sgn;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment