Rational Ratio

题目连接

题意:

  给一个无限循环小数,并给出它的循环节长度,让你把这个小数转化为分数

思路:

 这里先说一个结论,有了这个结论,就很好处理了,例如: 0.123123123… = 123 / 999 ,这样我们就可以把小数部分转化为分数,如果有整数部分,就先转小数,然后再进行合并,由于要求分数是最简,所以要进行化简
 这样就把问题完全解决了吗?并没有,如果第一个循环节前面有一部分小数呢?例如: 123.4565656…这样的话,我们可以把4提到整数部分,最后再除个十就可以了 也就是转化为 ---->(1234 + 56 / 99) * (1/10)这样这个问题才算是完全解决

丑陋的代码

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int inf = 0x7fffffff;
const int maxn = 2e5 + 5;
const int mod = 1e9 + 7;
const int dir8[8][2] = {
   
   {-1,0},{1,0},{0,-1},{0,1},{-1,-1},{-1,1},{1,-1},{1,1}};
const int dir14[4][2] = {
   
   {-1,0},{1,0},{0,-1},{0,1}};

ll GCD(ll a,ll b)
{
    ll temp;
    while(b){
        temp = a % b;
        a = b;
        b = temp;
    }
    return a;
}

ll atol(string a,int len,int &pos)
{
    ll sum = 0;
    for(int i = 0; i < len; i++){
        if(a[i] == '.'){
             pos = i;
            continue;
        }
        sum = sum * 10 + a[i] - '0';
    }
    return sum;
}

ll Get(int n)
{
    ll ans = 0;
    for(int i = 1; i <= n; i++){
        ans = ans * 10 + 9;
    }
    return ans;
}

int main()
{
    string str;
    int n;
    cin>>str>>n;
    ll fenmu = Get(n);
    int pos;
    ll pre = atol(str,str.size() - n,pos);
    ll suf = 0;
    for(int i = str.size() - n; i < str.size(); i++){
        suf = suf * 10 + str[i] - '0';
    }
    ll t = 1;
    for(int i = pos + 1; i < str.size() - n; i++){
        t *= 10;
    } 
    ll fenzi = fenmu * pre + suf;
    //cout << fenzi << endl;
    fenmu = fenmu * t;
    //cout << pre << ' ' << suf << ' ' << fenmu << ' ' << fenzi <<endl;
    ll gcd = GCD(fenzi,fenmu);
    cout << fenzi / gcd << '/' << fenmu / gcd<< endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/CUCUC1/article/details/110340949