java-求100的阶乘-100!(即100*99*98*...*2*1),不用BigInteger - 代码物语-Let code talk - ITeye技术网站
BigIntegerAddition.add见http://bylijinnan.iteye.com/blog/1463337
http://bylijinnan.iteye.com/blog/1463337
BigIntegerAddition.add见http://bylijinnan.iteye.com/blog/1463337
- public static String factorial(int n){
- if(n<=0){
- return null;
- }
- String result="1";
- String tmp="0";
- for(int i=2;i<=n;i++){
- for(int j=0;j<i;j++){
- //I write 'BigIntegerAddition' in my own BigIntegerAddition.java
- tmp=BigIntegerAddition.add(result, tmp);//String add(String,String)
- }
- result=tmp;
- tmp="0";
- }
- return result;
- }
http://bylijinnan.iteye.com/blog/1463337
- //return x+y. Have not considered the negative number yet.
- public static String add(String x,String y){
- if(x==null||y==null){
- return null;
- }
- if(!isNumeric(x)||!isNumeric(y)){
- return null;
- }
- if(x.equals("0")){
- return y;
- }
- if(y.equals("0")){
- return x;
- }
- if(x.length()>y.length()){
- String tmp=x;
- x=y;
- y=tmp;
- }
- x=addZeroToFirst(x,y.length());
- String z=addHelp(x,y);
- return z;
- }
- public static String addHelp(String x,String y){
- String z="";
- int len=x.length();
- int[] a=toIntArray(x);
- int[] b=toIntArray(y);
- int[] c=new int[len+1];
- int d=0;//to carry. No need to use int[]
- for(int i=0;i<len;i++){
- int tmpSum=a[len-1-i]+b[len-1-i]+d;
- c[len-i]=tmpSum%10;
- d=tmpSum/10;
- }
- c[0]=d;
- StringBuilder sb=new StringBuilder();
- for(int i=0;i<=len;i++){
- sb.append(c[i]);
- }
- if(c[0]==0){//delete the first '0' in result string
- z=sb.substring(1);
- }else{
- z=sb.toString();
- }
- return z;
- }
- //String - toCharArray - toIntArray
- public static int[] toIntArray(String str){
- int len=str.length();
- int[] result=new int[len];
- for(int i=0;i<len;i++){
- result[i]=str.charAt(i)-'0';
- }
- return result;
- }
- //("123",5)-->"00123"
- public static String addZeroToFirst(String str,int length){
- StringBuilder sb=new StringBuilder();
- int diff=length-str.length();
- while(diff>0){
- sb.append("0");
- diff--;
- }
- sb.append(str);
- return sb.toString();
- }
- public static boolean isNumeric(String str){
- Pattern p=Pattern.compile("[0-9]*");
- Matcher isNum=p.matcher(str);
- return isNum.matches();
- }