本题要求计算A/B,其中A是不超过1000位的正整数,B是1位正整数。你需要输出商数Q和余数R,使得A = B * Q + R成立。
自己代码:
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
int main(){
    string A;
    int B,Q,R; //Q是商,R是余数
    cin>>A>>B;
    int n = 0;
    //***处理第一位,因为这时候商0,不需要输出***/
    if((A[0]- '0') < B) n = (A[0] - '0') * 10 ;
    else {
        n = (A[0] - '0') % B * 10;
        cout<<(A[0] - '0') / B;
    }
    //***从第一位开始算起***//
    for(int i = 1;i < A.length();i++){
        n = A[i] + n;
        Q = (n - '0') / B;
        R = (n - '0') % B ;
        n = R * 10;
        cout<<Q;
    }
    cout<<' '<<R; 
}

评注:这道题目一开始就说是1000位的整数,所以肯定是用字符串去解决,算法实际上是模拟了除法的过程,转换为两位整数对一位整数的除与模。

参考代码:
链接:https://www.nowcoder.com/questionTerminal/25c3ae17bc99425b99542802ee882377
来源:牛客网

#include<iostream>
#include<string>
using namespace std;
int main(){
    string str,ans;
    int n,d = 0;
    cin >> str >> n;
    for(int i = 0; i <= str.size()-1; i++){
        int current = d * 10 + (str[i]-'0');
        ans += (current / n+'0');  //用了操作符重载
        d = current % n;
    }
    for(int i = (ans[0] == '0' && ans.size()!=1)?1:0; i < ans.size(); i++)
        cout << ans[i];
    cout << " " << d;
    return 0;
}

收获:参考代码处用了操作符重载进行字符串的相加,底层实际上是进行字符串的拼接,也就是调用.append()函数

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐