标签:
import java.util.Arrays;
/**
* 今天做美团的笔试题,遇到这个问题,花了点时间去处理;
* 代码实现了基本的功能,很多边界问题没有去考虑
* 存在以下问题
* 1,正负数没有考虑;
* 2.如果商也是大数的话代码结果会出错。
*
* @author 刘传武
*
*/
public class Solution {
public void div(String a, String b) {
char[] chara = a.toCharArray();
char[] charb = b.toCharArray();
int[] numa = new int[a.length()];
int[] numb = new int[b.length()];
for (int i = 0; i < charb.length; i++) {
numb[i] = charb[i]-‘0‘;
}
for (int i = 0; i < chara.length; i++) {
numa[i] = chara[i]-‘0‘;
}
int div=0;
while(compare(numa,numb)>0){
numa= div(numa,numb);
div ++;
}
StringBuffer sb = new StringBuffer();
sb.append(""+div+" ");
for (int i = 0; i < numa.length; i++) {
sb.append(""+numa[i]);
}
System.out.println(""+sb);
}
private int[] div(int[] numa, int[] numb) {
for (int i = 0; i < numb.length; i++) {
int tmpa = numa[numa.length-i-1];
int tmpb = numb[numb.length-i-1];
int sub = tmpa-tmpb;
int count = numa.length-1;
if (sub>=0) {
numa[numa.length-i-1] = sub;
}else{
numa[numa.length-i-1] = sub+10;
count =numa.length- i-1-1;
while(numa[count]==0){
numa[count] =9;
count--;
}
numa[count]--;
if (numa[0]==0) {
numa = Arrays.copyOfRange(numa,1, numa.length);
}
}
}
return numa;
}
int compare(int[] numa, int[] numb) {
if (numa.length<numb.length) {
return -1;
}else if (numa.length>numb.length) {
return 1;
}else{
for (int i = 0; i < numb.length; i++) {
if (numa[i]>numb[i]) {
return 1;
}
if (numa[i]<numb[i]) {
return -1;
}
}
return 0;
}
}
}
标签:
原文地址:http://www.cnblogs.com/liuchuanwu/p/4803011.html