How to calculate big numbers in java? - java

ex
I want the sum form 1^1 to n^n : 1^1 + 2^2 + 3^3 + .............+n^n
and I know how, but the problem that I want only the last ten numbers of the sum but I have only to use primitive data. how can I calculate large numbers using only primitive data.
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
short n = in.nextShort();
if(n < 0) {
System.out.println("please give a positive number");
return;
}
long l = rechnung(n);
System.out.println(l);
String str = Objects.toString(l, null);
String s = ziffer(str);
System.out.println(s);
}
public static long rechnung(short j) {
long summe = 0;
for(int i = 1; i <= j; i++) {
summe += Math.pow(i,i);
}
return summe;
}
public static String ziffer(String s) {
String str = "";
int k =s.length() - 10;
int cond = k + 9;
if(s.length() <= 10) {
return s;
}
for(int j = k; j <= cond; j++) {
str = str + s.charAt(j);
}
return str;
}

As you only need to keep the lower 10 digits you can use a % 10_000_000_000L to keep the digits you need with each calculation.

Related

Loop to add string of number

I try for an exercice to add
String nb = "135";
String nb2 = "135";
Result should be a String of "270"
I have no idea how to do that...I try to make a for loop and make an addition : nb.charAt(i) + nb2.charAt(i) but with no succes, I don't know what I have to do with the carry over.
EDIT : I try to don't use Integer or BigInteger, only String this is why I try to use a for loop.
Thanks for clue.
String str = "";
// Calculate length of both String
int n1 = nb.length(), n2 = nb2.length();
int diff = n2 - n1;
// Initially take carry zero
int carry = 0;
// Traverse from end of both Strings
for (int i = n1 - 1; i>=0; i--)
{
// Do school mathematics, compute sum of
// current digits and carry
int sum = ((int)(nb.charAt(i)-'0') +
(int) nb2.charAt(i+diff)-'0') + carry);
str += (char)(sum % 10 + '0');
carry = sum / 10;
}
// Add remaining digits of nb2[]
for (int i = n2 - n1 - 1; i >= 0; i--)
{
int sum = ((int) nb2.charAt(i) - '0') + carry);
str += (char)(sum % 10 + '0');
carry = sum / 10;
}
// Add remaining carry
if (carry > 0)
str += (char)(carry + '0');
// reverse resultant String
return new StringBuilder(str).reverse().toString();
try below snippet:
String s1 = "135";
String s2 = "135";
String result = Integer.toString (Integer.parseInt(s1)+Integer.parseInt(s2));
try converting char to int using Integer.parseInt(nb.charAt(i)) + Integer.parseInt(nb2.charAt(i))
you can use Character.numericValue to give you the integer value of a character, this will probably help you write the method. This method will also return -1 if there is no numeric value or -2 if it is fractional like the character for 1/2
You need to convert the strings to numbers to add them. Let's use BigInteger, just in case the numbers are really big:
String nb = "135";
String nb2 = "135";
BigInteger num1 = new BigInteger(nb);
BigInteger num2 = new BigInteger(nb2);
String result = num1.add(num2).toString();
Do it as follows:
public class Main {
public static void main(String args[]) {
System.out.println(getSum("270", "270"));
System.out.println(getSum("3270", "270"));
System.out.println(getSum("270", "3270"));
}
static String getSum(String n1, String n2) {
StringBuilder sb = new StringBuilder();
int i, n, cf = 0, nl1 = n1.length(), nl2 = n2.length(), max = nl1 > nl2 ? nl1 : nl2, diff = Math.abs(nl1 - nl2);
for (i = max - diff - 1; i >= 0; i--) {
if (nl1 > nl2) {
n = cf + Integer.parseInt(String.valueOf(n1.charAt(i + diff)))
+ Integer.parseInt(String.valueOf(n2.charAt(i)));
} else {
n = cf + Integer.parseInt(String.valueOf(n1.charAt(i)))
+ Integer.parseInt(String.valueOf(n2.charAt(i + diff)));
}
if (n > 9) {
sb.append(n % 10);
cf = n / 10;
} else {
sb.append(n);
cf = 0;
}
}
if (nl1 > nl2) {
for (int j = i + 1; j >= 0; j--) {
sb.append(n1.charAt(j));
}
} else if (nl1 < nl2) {
for (int j = i + 1; j >= 0; j--) {
sb.append(n2.charAt(j));
}
}
return sb.reverse().toString();
}
}
Output:
540
3540
3540
I would like to propose a much cleaner solution that adds 2 positive numbers and returns the result. Just maintain a carry while adding 2 digits and add carry in the end if carry is greater than 0.
public class Main{
public static void main(String[] args) {
System.out.println(addTwoNumbers("135","135"));
}
private static String addTwoNumbers(String s1,String s2){
if(s1.length() < s2.length()) return addTwoNumbers(s2,s1);
StringBuilder result = new StringBuilder("");
int ptr2 = s2.length() - 1,carry = 0;
for(int i=s1.length()-1;i>=0;--i){
int res = s1.charAt(i) - '0' + (ptr2 < 0 ? 0 : s2.charAt(ptr2--) - '0') + carry;
result.append(res % 10);
carry = res / 10;
}
if(carry > 0) result.append(carry);
return trimLeadingZeroes(result.reverse().toString());
}
private static String trimLeadingZeroes(String str){
for(int i=0;i<str.length();++i){
if(str.charAt(i) != '0') return str.substring(i);
}
return "0";
}
}
Demo: https://onlinegdb.com/Sketpl-UL
Try this i hope it works for you
Code
public static int convert_String_To_Number(String numStr,String numStr2) {
char ch[] = numStr.toCharArray();
char ch2[] = numStr2.toCharArray();
int sum1 = 0;
int sum=0;
//get ascii value for zero
int zeroAscii = (int)'0';
for (char c:ch) {
int tmpAscii = (int)c;
sum = (sum*10)+(tmpAscii-zeroAscii);
}
for (char d:ch2) {
int tmpAscii = (int)d;
sum1 = (sum*10)+(tmpAscii-zeroAscii);
}
return sum+sum1;
}
public static void main(String a[]) {
System.out.println("\"123 + 123\" == "+convert_String_To_Number("123" , "123"));
}
}

java.lang.StringIndexOutOfBoundsException for the soln

This program is throwing java.lang.StringIndexOutOfBoundsException.
Prime numbers in a single long string: "2357111317192329..."
Test cases
Inputs:
(int) n = 0
Output:
(string) "23571"
Inputs:
(int) n = 3
Output:
(string) "71113"
public class Answer {
public static String answer(int n) {
int i = 0;
int num = 0;
String primeNumbers = "";
char[] ar = new char[5];
for (i = 1; i <= 10000; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
primeNumbers = primeNumbers + i;
}
}
ar[0] = primeNumbers.charAt(n);
ar[1] = primeNumbers.charAt(n + 1);
ar[2] = primeNumbers.charAt(n + 2);
ar[3] = primeNumbers.charAt(n + 3);
ar[4] = primeNumbers.charAt(n + 4);
return String.valueOf(ar);
}
}
try this solution:
public class Answer {
public static String answer(int n) {
StringBuilder primeNumberString = new StringBuilder(0);
int currentPrimeNumber = 2;
while (primeNumberString.length() < n+5) {
primeNumberString.append(currentPrimeNumber);
currentPrimeNumber++;
for (int index = 2; index < currentPrimeNumber; index++) {
if (currentPrimeNumber % index == 0) {
currentPrimeNumber++;
index = 2;
} else {
continue;
}
}
}
return primeNumberString.toString().substring(n, n+5)
}
}
=======================================================
EDIT
The problem statement suggests that the required output from the method you have written should be a string of length 5 and it should be from 'n' to 'n+4'.
Our goal should be to come up with a solution that gives us the string from n to n+4 using as less resources as possible and as fast as possible.
In the approach you have taken, you are adding in your string, all the prime numbers between 0 and 10000. Which comes up to about 1,229 prime numbers. The flaw in this approach is that if the input is something like 0. You are still building a string of 1,229 prime numbers which is totally unnecessary. If the input is something like 100000 then the error you are facing occurs, since you don't have a big enough string.
The best approach here is to build a string up to the required length which is n+5. Then cut the substring out of it. It's simple and efficient.
Probably you don't generate enough length of the string and given value out of your length of string.
I would recommend you to check your program on max value of given N. Also I would recommend you to not use String (read about creating a new object each time when you concatenate String) and simplify the second loop.
public static String answer(int n) {
StringBuilder sb = new StringBuilder("");
char[] ar = new char[5];
for (int i = 2; i <= 10000; i++) {
boolean flag = true;
for (int j = 2; j*j <= i; j++) {
if(i%j==0) {
flag = false;
break;
}
}
if(flag) {
sb.append(i);
}
}
ar[0] = sb.charAt(n);
ar[1] = sb.charAt(n + 1);
ar[2] = sb.charAt(n + 2);
ar[3] = sb.charAt(n + 3);
ar[4] = sb.charAt(n + 4);
return String.valueOf(ar);
}

Prime Factorization Program in Java Using Loops

I have to write a program that takes a number from the user and then displays the prime factors of the number. This is the program I have so far:
public static void main(String[] args) {
int a = getInt("Give a number: ");
int i = 0;
System.out.println("Your prime factors are: " + primeFactorization(a, i));
}
public static int getInt(String prompt) {
int input;
System.out.print(prompt);
input = console.nextInt();
return input;
}
public static int primeFactorization(int a, int i) {
for (i = 2; i <= a ; i++) {
while (a % i == 0) {
a /= i;
}
}
return i;
}
}
I can't figure out how to get it to print out the list of numbers. Any help is appreciated.
You should return a List<Integer> not a single int, and there is no point in i being an argument. A correct method is
public static List<Integer> primeFactorization(int a) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 2; i <= a ; i++) {
while (a % i == 0) {
list.add(i);
a /= i;
}
}
return list;
}
While #Paul Boddington's answer is better in most cases (i.e. if you are using the values afterwards), for a simple program like yours, you could add all of the factors to a string and return the string. For example:
public static String primeFactorization(int a) {
String factors = "";
for (int i = 2; i <= a ; i++) {
while (a % i == 0) {
factors += i + " ";
a /= i;
}
}
return factors;
}

Check Credit Card Validity using Luhn Algorithm

I tried to check the validation of credit card using Luhn algorithm, which works as the following steps:
Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number.
2 * 2 = 4
2 * 2 = 4
4 * 2 = 8
1 * 2 = 2
6 * 2 = 12 (1 + 2 = 3)
5 * 2 = 10 (1 + 0 = 1)
8 * 2 = 16 (1 + 6 = 7)
4 * 2 = 8
Now add all single-digit numbers from Step 1.
4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37
Add all digits in the odd places from right to left in the card number.
6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38
Sum the results from Step 2 and Step 3.
37 + 38 = 75
If the result from Step 4 is divisible by 10, the card number is valid; otherwise, it is invalid. For example, the number 4388576018402626 is invalid, but the number 4388576018410707 is valid.
Simply, my program always displays valid for everything that I input. Even if it's a valid number and the result of sumOfOddPlace and sumOfDoubleEvenPlace methods are equal to zero. Any help is appreciated.
import java.util.Scanner;
public class CreditCardValidation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
long array[] = new long [16];
do
{
count = 0;
array = new long [16];
System.out.print("Enter your Credit Card Number : ");
long number = in.nextLong();
for (int i = 0; number != 0; i++) {
array[i] = number % 10;
number = number / 10;
count++;
}
}
while(count < 13);
if ((array[count - 1] == 4) || (array[count - 1] == 5) || (array[count - 1] == 3 && array[count - 2] == 7)){
if (isValid(array) == true) {
System.out.println("\n The Credit Card Number is Valid. ");
} else {
System.out.println("\n The Credit Card Number is Invalid. ");
}
} else{
System.out.println("\n The Credit Card Number is Invalid. ");
}
}
public static boolean isValid(long[] array) {
int total = sumOfDoubleEvenPlace(array) + sumOfOddPlace(array);
if ((total % 10 == 0)) {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return true;
} else {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long[] array) {
int result = 0;
for (int i=0; i< array.length; i++)
{
while (array[i] > 0) {
result += (int) (array[i] % 10);
array[i] = array[i] / 100;
}}
System.out.println("\n The sum of odd place is " + result);
return result;
}
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
long temp = 0;
for (int i=0; i< array.length; i++){
while (array[i] > 0) {
temp = array[i] % 100;
result += getDigit((int) (temp / 10) * 2);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of double even place is " + result);
return result;
}
}
You can freely import the following code:
public class Luhn
{
public static boolean Check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
}
Link reference: https://github.com/jduke32/gnuc-credit-card-checker/blob/master/CCCheckerPro/src/com/gnuc/java/ccc/Luhn.java
Google and Wikipedia are your friends. Instead of long-array I would use int-array. On Wikipedia following java code is published (together with detailed explanation of Luhn algorithm):
public static boolean check(int[] digits) {
int sum = 0;
int length = digits.length;
for (int i = 0; i < length; i++) {
// get digits in reverse order
int digit = digits[length - i - 1];
// every 2nd number multiply with 2
if (i % 2 == 1) {
digit *= 2;
}
sum += digit > 9 ? digit - 9 : digit;
}
return sum % 10 == 0;
}
You should work on your input processing code. I suggest you to study following solution:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean repeat;
List<Integer> digits = new ArrayList<Integer>();
do {
repeat = false;
System.out.print("Enter your Credit Card Number : ");
String input = in.next();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c < '0' || c > '9') {
repeat = true;
digits.clear();
break;
} else {
digits.add(Integer.valueOf(c - '0'));
}
}
} while (repeat);
int[] array = new int[digits.size()];
for (int i = 0; i < array.length; i++) {
array[i] = Integer.valueOf(digits.get(i));
}
boolean valid = check(array);
System.out.println("Valid: " + valid);
}
I took a stab at this with Java 8:
public static boolean luhn(String cc) {
final boolean[] dbl = {false};
return cc
.chars()
.map(c -> Character.digit((char) c, 10))
.map(i -> ((dbl[0] = !dbl[0])) ? (((i*2)>9) ? (i*2)-9 : i*2) : i)
.sum() % 10 == 0;
}
Add the line
.replaceAll("\\s+", "")
Before
.chars()
If you want to handle whitespace.
Seems to produce identical results to
return LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(cc);
From Apache's commons-validator.
There are two ways to split up your int into List<Integer>
Use %10 as you are using and store it into a List
Convert to a String and then take the numeric values
Here are a couple of quick examples
public static void main(String[] args) throws Exception {
final int num = 12345;
final List<Integer> nums1 = splitInt(num);
final List<Integer> nums2 = splitString(num);
System.out.println(nums1);
System.out.println(nums2);
}
private static List<Integer> splitInt(int num) {
final List<Integer> ints = new ArrayList<>();
while (num > 0) {
ints.add(0, num % 10);
num /= 10;
}
return ints;
}
private static List<Integer> splitString(int num) {
final List<Integer> ints = new ArrayList<>();
for (final char c : Integer.toString(num).toCharArray()) {
ints.add(Character.getNumericValue(c));
}
return ints;
}
I'll use 5 digit card numbers for simplicity. Let's say your card number is 12345; if I read the code correctly, you store in array the individual digits:
array[] = {1, 2, 3, 4, 5}
Since you already have the digits, in sumOfOddPlace you should do something like
public static int sumOfOddPlace(long[] array) {
int result = 0;
for (int i = 1; i < array.length; i += 2) {
result += array[i];
}
return result;
}
And in sumOfDoubleEvenPlace:
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
for (int i = 0; i < array.length; i += 2) {
result += getDigit(2 * array[i]);
}
return result;
}
this is the luhn algorithm implementation which I use for only 16 digit Credit Card Number
if(ccnum.length()==16){
char[] c = ccnum.toCharArray();
int[] cint = new int[16];
for(int i=0;i<16;i++){
if(i%2==1){
cint[i] = Integer.parseInt(String.valueOf(c[i]))*2;
if(cint[i] >9)
cint[i]=1+cint[i]%10;
}
else
cint[i] = Integer.parseInt(String.valueOf(c[i]));
}
int sum=0;
for(int i=0;i<16;i++){
sum+=cint[i];
}
if(sum%10==0)
result.setText("Card is Valid");
else
result.setText("Card is Invalid");
}else
result.setText("Card is Invalid");
If you want to make it use on any number replace all 16 with your input number length.
It will work for Visa number given in the question.(I tested it)
Here's my implementation of the Luhn Formula.
/**
* Runs the Luhn Equation on a user inputed CCN, which in turn
* determines if it is a valid card number.
* #param c A user inputed CCN.
* #param cn The check number for the card.
* #return If the card is valid based on the Luhn Equation.
*/
public boolean luhn (String c, char cn)
{
String card = c;
String checkString = "" + cn;
int check = Integer.valueOf(checkString);
//Drop the last digit.
card = card.substring(0, ( card.length() - 1 ) );
//Reverse the digits.
String cardrev = new StringBuilder(card).reverse().toString();
//Store it in an int array.
char[] cardArray = cardrev.toCharArray();
int[] cardWorking = new int[cardArray.length];
int addedNumbers = 0;
for (int i = 0; i < cardArray.length; i++)
{
cardWorking[i] = Character.getNumericValue( cardArray[i] );
}
//Double odd positioned digits (which are really even in our case, since index starts at 0).
for (int j = 0; j < cardWorking.length; j++)
{
if ( (j % 2) == 0)
{
cardWorking[j] = cardWorking[j] * 2;
}
}
//Subtract 9 from digits larger than 9.
for (int k = 0; k < cardWorking.length; k++)
{
if (cardWorking[k] > 9)
{
cardWorking[k] = cardWorking[k] - 9;
}
}
//Add all the numbers together.
for (int l = 0; l < cardWorking.length; l++)
{
addedNumbers += cardWorking[l];
}
//Finally, check if the number we got from adding all the other numbers
//when divided by ten has a remainder equal to the check number.
if (addedNumbers % 10 == check)
{
return true;
}
else
{
return false;
}
}
I pass in the card as c which I get from a Scanner and store in card, and for cn I pass in checkNumber = card.charAt( (card.length() - 1) );.
Okay, this can be solved with a type conversions to string and some Java 8
stuff. Don't forget numbers and the characters representing numbers are not the same. '1' != 1
public static int[] longToIntArray(long cardNumber){
return Long.toString(cardNumber).chars()
.map(x -> x - '0') //converts char to int
.toArray(); //converts to int array
}
You can now use this method to perform the luhn algorithm:
public static int luhnCardValidator(int cardNumbers[]) {
int sum = 0, nxtDigit;
for (int i = 0; i<cardNumbers.length; i++) {
if (i % 2 == 0)
nxtDigit = (nxtDigit > 4) ? (nxtDigit * 2 - 10) + 1 : nxtDigit * 2;
sum += nxtDigit;
}
return (sum % 10);
}
private static int luhnAlgorithm(String number){
int n=0;
for(int i = 0; i<number.length(); i++){
int x = Integer.parseInt(""+number.charAt(i));
n += (x*Math.pow(2, i%2))%10;
if (x>=5 && i%2==1) n++;
}
return n%10;
}
public class Creditcard {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String cardno = sc.nextLine();
if(checkType(cardno).equals("U")) //checking for unknown type
System.out.println("UNKNOWN");
else
checkValid(cardno); //validation
}
private static String checkType(String S)
{
int AM=Integer.parseInt(S.substring(0,2));
int D=Integer.parseInt(S.substring(0,4)),d=0;
for(int i=S.length()-1;i>=0;i--)
{
if(S.charAt(i)==' ')
continue;
else
d++;
}
if((AM==34 || AM==37) && d==15)
System.out.println("AMEX");
else if(D==6011 && d==16)
System.out.println("Discover");
else if(AM>=51 && AM<=55 && d==16)
System.out.println("MasterCard");
else if(((S.charAt(0)-'0')==4)&&(d==13 || d==16))
System.out.println("Visa");
else
return "U";
return "";
}
private static void checkValid(String S) // S--> cardno
{
int i,d=0,sum=0,card[]=new int[S.length()];
for(i=S.length()-1;i>=0;i--)
{
if(S.charAt(i)==' ')
continue;
else
card[d++]=S.charAt(i)-'0';
}
for(i=0;i<d;i++)
{
if(i%2!=0)
{
card[i]=card[i]*2;
if(card[i]>9)
sum+=digSum(card[i]);
else
sum+=card[i];
}
else
sum+=card[i];
}
if(sum%10==0)
System.out.println("Valid");
else
System.out.println("Invalid");
}
public static int digSum(int n)
{
int sum=0;
while(n>0)
{
sum+=n%10;
n/=10;
}
return sum;
}
}
Here is the implementation of Luhn algorithm.
public class LuhnAlgorithm {
/**
* Returns true if given card number is valid
*
* #param cardNum Card number
* #return true if card number is valid else false
*/
private static boolean checkLuhn(String cardNum) {
int cardlength = cardNum.length();
int evenSum = 0, oddSum = 0, sum;
for (int i = cardlength - 1; i >= 0; i--) {
System.out.println(cardNum.charAt(i));
int digit = Character.getNumericValue(cardNum.charAt(i));
if (i % 2 == 0) {
int multiplyByTwo = digit * 2;
if (multiplyByTwo > 9) {
/* Add two digits to handle cases that make two digits after doubling */
String mul = String.valueOf(multiplyByTwo);
multiplyByTwo = Character.getNumericValue(mul.charAt(0)) + Character.getNumericValue(mul.charAt(1));
}
evenSum += multiplyByTwo;
} else {
oddSum += digit;
}
}
sum = evenSum + oddSum;
if (sum % 10 == 0) {
System.out.println("valid card");
return true;
} else {
System.out.println("invalid card");
return false;
}
}
public static void main(String[] args) {
String cardNum = "4071690065031703";
System.out.println(checkLuhn(cardNum));
}
}
public class LuhnAlgorithm {
/**
* Returns true if given card number is valid
*
* #param cardNum Card number
* #return true if card number is valid else false
*/
private static boolean checkLuhn(String cardNum) {
int cardlength = cardNum.length();
int evenSum = 0, oddSum = 0, sum;
for (int i = cardlength - 1; i >= 0; i--) {
System.out.println(cardNum.charAt(i));
int digit = Character.getNumericValue(cardNum.charAt(i));
if (i % 2 == 0) {
int multiplyByTwo = digit * 2;
if (multiplyByTwo > 9) {
/* Add two digits to handle cases that make two digits after doubling */
String mul = String.valueOf(multiplyByTwo);
multiplyByTwo = Character.getNumericValue(mul.charAt(0)) + Character.getNumericValue(mul.charAt(1));
}
evenSum += multiplyByTwo;
} else {
oddSum += digit;
}
}
sum = evenSum + oddSum;
if (sum % 10 == 0) {
System.out.println("valid card");
return true;
} else {
System.out.println("invalid card");
return false;
}
}
public static void main(String[] args) {
String cardNum = "8112189875";
System.out.println(checkLuhn(cardNum));
}
}
Hope it may works.
const options = {
method: 'GET',
headers: {Accept: 'application/json', 'X-Api-Key': '[APIkey]'}
};
fetch('https://api.epaytools.com/Tools/luhn?number=[CardNumber]&metaData=true', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));

Count of most occurring digit... Find the digit that occurs most in a given number

the following s the code to
Find the number of occurrences of a given digit in a number.wat shall i do in order to Find the digit that occurs most in a given number.(should i create array and save those values and then compare)
can anyone please help me ..
import java.util.*;
public class NumOccurenceDigit
{
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("Enter a Valid Digit.(contaioning only numerals)");
int number = s.nextInt();
String numberStr = Integer.toString(number);
int numLength = numberStr.length();
System.out.println("Enter numer to find its occurence");
int noToFindOccurance = s.nextInt();
String noToFindOccuranceStr = Integer.toString(noToFindOccurance);
char noToFindOccuranceChar=noToFindOccuranceStr.charAt(0);
int count = 0;
char firstChar = 0;
int i = numLength-1;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
static void recFunNumOccurenceDigit(char firstChar,int count,int i,char noToFindOccuranceChar,String numberStr)
{
if(i >= 0)
{
firstChar = numberStr.charAt(i);
if(firstChar == noToFindOccuranceChar)
//if(a.compareTo(noToFindOccuranceStr) == 0)
{
count++;
}
i--;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
else
{
System.out.println("The number of occurance of the "+noToFindOccuranceChar+" is :"+count);
System.exit(0);
}
}
}
/*
* Enter a Valid Digit.(contaioning only numerals)
456456
Enter numer to find its occurence
4
The number of occurance of the 4 is :2*/
O(n)
keep int digits[] = new int[10];
every time encounter with digit i increase value of digits[i]++
the return the max of digits array and its index. that's all.
Here is my Java code:
public static int countMaxOccurence(String s) {
int digits[] = new int[10];
for (int i = 0; i < s.length(); i++) {
int j = s.charAt(i) - 48;
digits[j]++;
}
int digit = 0;
int count = digits[0];
for (int i = 1; i < 10; i++) {
if (digits[i] > count) {
count = digits[i];
digit = i;
}
}
System.out.println("digit = " + digit + " count= " + count);
return digit;
}
and here are some tests
System.out.println(countMaxOccurence("12365444433212"));
System.out.println(countMaxOccurence("1111111"));
declare a count[] array
and change your find function to something like
//for (i = 1 to n)
{
count[numberStr.charAt(i)]++;
}
then find the largest item in count[]
public class Demo{
public static void main(String[] args) {
System.out.println("Result: " + maxOccurDigit(327277));
}
public static int maxOccurDigit(int n) {
int maxCount = 0;
int maxNumber = 0;
if (n < 0) {
n = n * (-1);
}
for (int i = 0; i <= 9; i++) {
int num = n;
int count = 0;
while (num > 0) {
if (num % 10 == i) {
count++;
}
num = num / 10;
}
if (count > maxCount) {
maxCount = count;
maxNumber = i;
} else if (count == maxCount) {
maxNumber = -1;
}
}
return maxNumber;
}}
The above code returns the digit that occur the most in a given number. If there is no such digit, it will return -1 (i.e.if there are 2 or more digits that occurs same number of times then -1 is returned. For e.g. if 323277 is passed then result is -1). Also if a number with single digit is passed then number itself is returned back. For e.g. if number 5 is passed then result is 5.

Categories