题目描述
给定两个非负整数A,B,请你计算 A / B的商和余数。
输入格式
共两行,第一行包含整数A,第二行包含整数B。
输出格式
共两行,第一行输出所求的商,第二行输出所求余数。
数据范围
1≤A的长度≤100000,
1≤B≤10000
B 一定不为0
输入样例:
7
2
输出样例:
3
1
观众老爷们,如果本思路对您有帮助,求关注一波~~~
思路
除法的思路
数组A[]: 1 2 6
数b 25
模拟过程
初始化余数r = 0
((r = 0) * 10 + (A[0] = 1)) / 25 = 0 ... r = 1
((r = 1) * 10 + (A[1] = 2)) / 25 = 0 ... r = 12
((r = 12) * 10 + (A[2] = 2)) / 25 = 5 ... r = 1
A遍历完,得到商和余数
初始化余数r = 0
计算乘法r = r * 10 + A[i] 其中A[i]为数组中的第i个数, b为数, r用来存储当前的结果
计算结果值 r / 10
计算余数,用于下次计算 r = r / 10
vector<int> C;
r = 0;
for(int i = A.size() - 1; i >= 0; i --){
r = r * 10 + A[i];
C.push_back(r / b);
r %= b;
}
reverse(C.begin(), C.end());
// 126 / 25 = 005 ... 1. 从C中去除00
while(C.size() > 1 && C.back() == 0) C.pop_back();
return C;
java
import java.util.Scanner;
public class Main{
static int r;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String a = sc.next();
int b = sc.nextInt();
char[] A = new char[a.length()];
for(int i = a.length() - 1; i >= 0; i --) A[a.length() - 1 - i] = a.charAt(i);
String res = div(A, b);
System.out.println(res);
System.out.println(r);
}
public static String div(char[] A, int b){
StringBuffer sb = new StringBuffer();
r = 0;
for(int i = A.length - 1; i >= 0; i --){
r = r * 10 + A[i] - '0';
sb.append(r / b);
r %= b;
}
String s = sb.toString();
int i = 0;
for(; i < s.length()- 1; i++){
if(s.charAt(i) != '0') break;
}
return s.substring(i, s.length());
}
}
python
r = 0; #记录余数
def div(A, b):
C = list()
global r
r = 0
i = 0
for i in range(len(A) - 1, -1, -1):
r = r * 10 + A[i]
C.append(int(r / b))
r %= b
while(len(C) > 1 and C[0] == 0):
C.pop(0)
return C
def main():
A = list(map(int, input()))
b = int(input())
A = A[::-1]
res = div(A, b)
print(''.join(map(str, res)))
print(r)
main()
c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> div(vector<int> &A, int b, int &r){
vector<int> C;
r = 0;
for(int i = A.size() - 1; i >= 0; i --){
r = r * 10 + A[i];
C.push_back(r / b);
r %= b;
}
reverse(C.begin(), C.end());
while(C.size() > 1 && C.back() == 0) C.pop_back();
return C;
}
int main(){
string a;
int b;
cin >> a >> b;
vector<int> A;
for(int i = a.size() - 1; i >= 0; i --) A.push_back(a[i] - '0');
int r;
auto C = div(A, b, r);
for(int i = C.size() - 1; i >= 0; i --) printf("%d", C[i]);
cout << endl << r << endl;
return 0;
}
全能哥