smatskevich

LnipLesson4

Oct 10th, 2021 (edited)
1,297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include <algorithm>
  2. #include <exception>
  3. #include <iostream>
  4. #include <string>
  5.  
  6. typedef long long ll;
  7.  
  8. int main2() {
  9.   int n = 0;
  10.   int base = 10;
  11.   std::cin >> n >> base;
  12.   std::string result;
  13.   while (n > 0) {
  14.     char c = char(n % base) + '0';
  15.     n /= base;
  16.     result += c;
  17.   }
  18.   std::reverse(result.begin(), result.end());
  19.   std::cout << result << std::endl;
  20. }
  21.  
  22. int CharToInt(char c) {
  23.   if (c >= '0' && c <= '9') return c - '0';
  24.   if (c >= 'A' && c <= 'Z') return c - 'A' + 10;
  25.   if (c >= 'a' && c <= 'z') return c - 'a' + 10;
  26.   throw std::runtime_error("Very Bad Symbol");
  27. }
  28.  
  29. ll Str2Int(std::string& s, int base) {
  30.   ll result = 0;
  31.   // Схема Горнера.
  32. //  result = (((s[0]*10 + s[1])* 10 + s[2])*10 + s[3])*10 + ... + s[l-1];
  33.   for (int i = 0; i < s.length(); ++i) {
  34.     result = result * base + CharToInt(s[i]);
  35.   }
  36.   return result;
  37. }
  38.  
  39. int main() {
  40.   std::string s;
  41.   int base = 10;
  42.   std::cin >> s >> base;
  43.  
  44.   try {
  45.     std::cout << Str2Int(s, base) << std::endl;
  46.   } catch (std::runtime_error& e) {
  47.     std::cout << e.what();
  48.   }
  49.   return 0;
  50. }
  51.  
Add Comment
Please, Sign In to add comment