zoukankan      html  css  js  c++  java
  • 51Nod 1873 初中的算术

    大神的字符串快速幂

     1 #include <iostream>
     2 #include <string>
     3 #include <algorithm>
     4 #include <cstdio>
     5 #include <cstring>
     6 using namespace std;
     7 
     8 //字符串的乘法
     9 string multi(string a, string b){
    10     int i, j, arr[200], len = a.length() + b.length();
    11     memset(arr, 0, sizeof arr);
    12     reverse(a.begin(), a.end());
    13     reverse(b.begin(), b.end());
    14     for (int i = 0; i<a.length(); i++)
    15     for (int j = 0; j<b.length(); j++)
    16         arr[i + j] += (a[i] - '0')*(b[j] - '0');
    17     for (int i = 0; i<len; i++){
    18         arr[i + 1] += arr[i] / 10;
    19         arr[i] %= 10;
    20     }
    21     string ret = string(len, '0');
    22     for (int i = 0; i<len; i++)
    23         ret[i] += arr[i];
    24     reverse(ret.begin(), ret.end());//翻转
    25     return ret;
    26 }
    27 string Str_Pow(string x, int p){
    28     string ret = "1";
    29     while (p){
    30         if (p & 1) ret = multi(ret, x);
    31         x = multi(x, x);
    32         p >>= 1;
    33     }
    34     return ret;
    35 }
    36 int main(){
    37     string a;
    38     int n;
    39     while (cin >> a >> n){
    40         int index = a.find('.');
    41         if (index == -1) index = 0;
    42         else {
    43             //substr() 是字符串截取函数
    44             a = a.substr(0, index) + a.substr(index + 1);
    45             index = (a.length() - index)*n;
    46         }
    47         a = Str_Pow(a, n);
    48         a = a.substr(0, a.length() - index) + "." + a.substr(a.length() - index);
    49         int i;
    50         for (i = 0; i<a.length(); i++)
    51             if (a[i] != '0')
    52                 break;
    53         //substr(i) 从i到end
    54         a = a.substr(i);
    55         for (int i = a.length() - 1; i >= 0; i--){
    56             if (a[i] == '.'){
    57                 a = a.substr(0, i); 
    58                 break;
    59             }
    60             else if (a[i] != '0'){
    61                 a = a.substr(0, i + 1);
    62                 break;
    63             }
    64         }
    65         cout << a << endl;
    66     }
    67     return 0;
    68 }
  • 相关阅读:
    shell脚本之数组
    shell脚本之函数
    shell脚本之sed
    shell脚本的for循环与read
    shell脚本之if语句
    shell脚本正则表达式
    shell的编程原理
    《梦断代码》阅读笔记03
    12.19学习总结
    《梦断代码》阅读笔记02
  • 原文地址:https://www.cnblogs.com/ouyang_wsgwz/p/8732466.html
Copyright © 2011-2022 走看看