Question: 

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.

Example:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99])



public class CountNumberWithUniqueDigits {



public static void main(String[] args) {
int n1[]={1,2,3,4,5,6,7,8,9,10,11,12};
for(int i=0;i<n1.length;i++){
System.out.println(n1[i]+" "+countnumber(n1[i]));
}
System.out.println("---------------------");
for(int i=0;i<n1.length;i++){
System.out.println(n1[i]+" "+countnumber1(n1[i]));
}
}
//method 1
public static int search(long prev,long max, boolean[] used){
int count=0;
if(prev<max){
count+=1;
}else{
return count;
}
for(int i=0;i<10;i++){
if(!used[i]){
used[i]=true;
long cur=10*prev+i;
int tmp=search(cur,max,used);
used[i]=false;
if(tmp==0){
break;
}
count+=tmp;
}
}
return count;
}

public static int countnumber(int n){
if(n>10){
return countnumber(10);
}
int count=1;
long max=(long)Math.pow(10, n);
boolean used[]=new boolean[10];
for(int i=1;i<10;i++){
used[i]=true;
count+=search(i,max,used);
used[i]=false;
}
return count;
}
//method 2
public static int countnumber1(int n){
if((n>=1)&&(n<=10)){
int count=0;
for(int i=1;i<=n;i++){
count+=findndigits(i);
}
return count;
}else{
return countnumber1(10);
}
}
public static int findndigits(int n){
if(n==1){
return 10;
}else if(n==2){
return 9*9;
}else if((n>2)&&(n<=10)){
return findndigits(n-1)*(11-n);
}else{
return 0;
}
}


}
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐