加一

来源:互联网 发布:新买的mac电池循环次数 编辑:程序博客网 时间:2024/04/27 23:47
给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。
该数字按照大小进行排列,最大的数在列表的最前面。
样例
给定 [1,2,3] 表示 123, 返回 [1,2,4].

给定 [9,9,9] 表示 999, 返回 [1,0,0,0].


import java.util.Scanner;import java.util.Stack;/** * 给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。该数字按照大小进行排列,最大的数在列表的最前面。样例给定 [1,2,3] 表示 123, 返回 [1,2,4].给定 [9,9,9] 表示 999, 返回 [1,0,0,0]. * @author Dell * */public class Test407 { public static void plus(int[] digits) {   Stack<Integer> s=new Stack<>();int c=0;for(int i=digits.length-1;i>=0;i--){if(i==digits.length-1){ if(digits[i]+1==10)  {s.push(0);  c=1;  if(i==0)  {  s.push(1);  }  }else{s.push(digits[i]+1);}}else{if(c==0){s.push(digits[i]);}else if(c==1){if(digits[i]+1==10){s.push(0);c=1;if(i==0){s.push(1);}}else{s.push(digits[i]+1);c=0;}}}}int [] plusOne =new int[s.size()];int k=0;while(s.isEmpty()!=true){plusOne[k++]=s.pop();}for(int i=0;i<plusOne.length;i++){System.out.print(plusOne[i]+" ");} }public static void main(String[] args) {  Scanner sc=new Scanner(System.in);  int n=sc.nextInt();  int[] a=new int[n];  for(int i=0;i<a.length;i++)  {  a[i]=sc.nextInt();  }  plus(a);}}


原创粉丝点击