Let's assume it means two consecutive digits can not be the same. If it means that all digits are unique the logic is very similar as well.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int no = scan.nextInt();
int count = 0;
for(int i=1;i<=no;i++)
{
String a = Integer.toString(i);
char[] b =a.toCharArray();
Arrays.sort(b);
String x = new String(b);
// System.out.println("Sorted array:"+x);
int flag = 0;
if(a.length()>1)
{
for(int j=1;j<a.length();j++)
{
//System.out.println(b[j-1]+"=="+b[j]);
if( (b[j-1]==b[j]))
{
flag =1;
// System.out.println("Has Repeated Numbers!");
break;
}
}
}
if(flag == 0)
{
count++;
// System.out.println("count:"+count+" --> "+"No:"+a);
}
}
System.out.println("Final Count:"+count);
}
}
INPUT 1: 3456
OUTPUT 1: 2562
INPUT 2: 22
OUTPUT 2: 20
INPUT 3: 7
OUTPUT 3: 7
INPUT 4: 100
OUTPUT 4: 90
INPUT 5: 37
OUTPUT 5: 34
My code satisfies input test cases from 2 to 5 but not for input 1. I understand that every digit should be unique in a number. Can anyone say where I have done my mistake in my logic from the code for input1?
Use regex!
int count = IntStream.rangeClosed(1, n)
.mapToObj(Integer::toString)
.filter(s -> s.matches("(?!.*?(.)\\1).*"))
.count();
What gone wrong in my logic is here I assumed no two digits can be the same , but the looking keenly on the problem statement it says no two consecutive digits can not be the same .
Here is the working code for the above input test cases. Thanks to Paul Hankin for pointing out.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int no = scan.nextInt();
int count = 0;
for(int i=1;i<=no;i++)
{
String a = Integer.toString(i);
char[] b =a.toCharArray();
int flag = 0;
if(a.length()>1)
{
for(int j=1;j<a.length();j++)
{
//System.out.println(b[j-1]+"=="+b[j]);
if( (b[j-1]==b[j]))
{
flag =1;
// System.out.println("Has Repeated Numbers!");
break;
}
}
}
if(flag == 0)
{
count++;
//System.out.println("count:"+count+" --> "+"No:"+a);
}
}
System.out.println(count);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.