资源描述:
《华为机试-两数相加相减.pdf》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、华为机试-两数相加相减示例输入:num1="580"num2="-50"输出:result="530"输入:num1="580"num2="-600"输出:result="-20"packagehuaweiTest.bigIntegerOperation;importjava.util.Stack;publicclassMain{/***@paramargs*/publicstaticvoidmain(String[]args){//TODOAuto-generatedmethodstubchar[
2、]num1="-000".toCharArray();char[]num2="-000".toCharArray();StringBufferresult=newStringBuffer();add(num1,num2,result);System.out.println(result);}privatestaticvoidadd(char[]num1,char[]num2,StringBufferresult){StacktheResult=null;//两正数相加if(num1[
3、0]!='-'&&num2[0]!='-'){theResult=numAdd(num1,num2);}//两负数相加elseif(num1[0]=='-'&&num2[0]=='-'){num1[0]='0';num2[0]='0';theResult=numAdd(num1,num2);if(theResult.size()!=1
4、
5、(theResult.size()==1&&!theResult.peek().equals("0")))theResult.push("-");}//负数+正数e
6、lseif(num1[0]=='-'&&num2[0]!='-'){//判断num1除去负号的长度是否大于num2的长度,好调用两正数相减的方法。if((num1.length-1)>num2.length){num1[0]='0';theResult=numSub(num1,num2);if(theResult.size()!=1
7、
8、(theResult.size()==1&&!theResult.peek().equals("0")))theResult.push("-");}elseif((n
9、um1.length-1)num1[i+1]){mark=true;break;}if(mark)theResult=numSub(num2,num1);else{theResult=numSub(num1,num
10、2);if(theResult.size()!=1
11、
12、(theResult.size()==1&&!theResult.peek().equals("0")))theResult.push("-");}}}//正数+负数elseif(num1[0]!='-'&&num2[0]=='-'){if((num2.length-1)>num1.length){num2[0]=0;theResult=numSub(num2,num1);if(theResult.size()!=1
13、
14、(theResult.si
15、ze()==1&&!theResult.peek().equals("0")))theResult.push("-");}elseif((num2.length-1)num2[i+1])mark=true;if(mark)theResult=n
16、umSub(num1,num2);else{theResult=numSub(num2,num1);if(theResult.size()!=1
17、
18、(theResult.size()==1&&!theResult.peek().equals("0")))theResult.push("-");}}}while(!theResult.isEmpty())result.append(theResult.pop());}privatestaticStackn