Playing with Digits in Java
Here you are given with an Integer, you need to display the count of non-repeated integers starting from 1 to till that number.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class PlayingWithDigits { | |
public static int playingWithDigits(int input1) | |
{ | |
int output1=0,output2=0,output=0,count=0; | |
for(int k=1;k<=input1;k++){ | |
if(k<100){ | |
if(k%11==0){ | |
count++; //with in 100 we can divide it with 11, to get repeated counts. | |
} | |
output1=count; | |
}else{ | |
String x=String.valueOf(k); | |
char [] c=x.toCharArray(); | |
for(int i=0,j=i+1;i<c.length && j<c.length;i++,j++){ | |
String y=String.valueOf(c[i]); | |
String z=String.valueOf(c[j]); | |
if(y.equals(z)){ | |
count=1; //here we are converting integer to string so that checking repeated values will be easy. | |
break; //if digits is repeated, then it breaks the loop. | |
}else{ | |
count=0; //if digits is not repeated then counter is zero. | |
} | |
} | |
output2+=count; //now we are saving counts of repeated values. | |
} | |
} | |
output=output1+output2; //combining repeated counts as one. | |
int finalOutput=input1-output; //finally we need to show output as non-repeated so we are subtracting with input repeated counts. | |
return finalOutput; | |
} | |
public static void main (String [] args){ | |
Scanner in = new Scanner(System.in); | |
int output = 0; | |
int ip1 = Integer.parseInt(in.nextLine().trim()); | |
output = playingWithDigits(ip1); | |
System.out.println(String.valueOf(output)); | |
in.close(); | |
} | |
} | |
Input
7
Output: 7 as there are no repeated counts from 1 to 7.
similarly
Input : 100
Output: 10 (11,22,33,44,55,66,77,88,99,100 these are the repeated digit counts from 1 to 100).
7
Output: 7 as there are no repeated counts from 1 to 7.
similarly
Input : 100
Output: 10 (11,22,33,44,55,66,77,88,99,100 these are the repeated digit counts from 1 to 100).
Comments
Post a Comment