面试中遇到一道大数相加算法题

题目大意

给一个数字123,放到数组中1 2 3,对数字进行加1,变成124

思路

求出数字长度,数字放到数组中,对数组第一个元素加1,对数组进行进位处理

 1 import java.util.Scanner;
 2 
 3 public class BigNumAdd {
 4     public void getNumAddOne(int num){
 5         int count = 0 ;
 6         int temp = num;
 7         
 8         if(num < Integer.MAX_VALUE && num >= Integer.MIN_VALUE )            //如果在int范围内可以直接+1
 9         {
10             System.out.println(num + 1);        
11             return;
12         }
13         
14         while(temp != 0){                                                    //求出数字长度
15             temp = temp / 10;
16             count ++;
17         }//while
18         
19         int arrayOfNum[] = new int[count + 1];                                //注意这里new的count+1个元素
20         temp = num;
21         for(int i = 0; i <= count; i++){                                    //数字放到数组中
22             arrayOfNum[i] = temp % 10;
23             temp = temp / 10;
24         }
25         arrayOfNum[0] += 1;
26         for(int i = 0; i < arrayOfNum.length - 1; i++){                        //对数组进行进位处理
27             if(arrayOfNum[i] >= 10){
28                 arrayOfNum[i] = arrayOfNum[i] % 10;
29                 arrayOfNum[i + 1] += 1;
30             }
31         }
32         
33         for(int i = arrayOfNum.length - 1; i >= 0; i--)                        //输出数组内容
34         {
35             if(i == arrayOfNum.length - 1 && arrayOfNum[arrayOfNum.length - 1] == 0)
36                 continue;
37             System.out.print(arrayOfNum[i]);
38         }
39     }//get
40     
41     public static void main(String args[]){
42         Scanner scanner = new Scanner(System.in);
43         int num = 0;
44         BigNumAdd bigNumAdd = new BigNumAdd();
45         
46         while((num  = scanner.nextInt()) != -1){
47             bigNumAdd.getNumAddOne(num);
48         }
49         scanner.close();
50     }
51 }

面试官后面问,有没有考虑边界问题。我说可能少new了一个元素,如果99的话会造成数组越界。后面他说如果小于10的整数呢

开始没理解,后面回来想了,他的意思应该是如果是int范围内的数字只要直接加1处理就好了。这样就不用执行后面的步骤了,这样效率会大大提高,这可能就是他说的边界条件吧

原文地址:https://www.cnblogs.com/luckygxf/p/4340996.html