Reverse and sum the number occurrence in string - java - java

I would like to write a function that will be reverse a number and then sum it up.
For example, the input string is
We have 55 guests in room 38
So the expected output should be
83 + 55 = 138
I have face a question is that I can't read the last number
example:
input string is '8 people'
output is 0
Here's the code I've written :
int total = 0;
String num = "";
String a = input.nextLine();
for (int i = a.length() - 1; i > 0; i--) {
if (Character.isDigit(a.charAt(i))) {
num += a.charAt(i);
if (!Character.isDigit(a.charAt(i - 1))) {
total += Integer.valueOf(num);
num = "";
}
}
}

All you really need to do is :
String input = "We have 55 guests in room 38";
int sum = 0;
String[] split = input.split(" "); // split based on space
for (int i = 0; i < split.length; i++) {
if (split[i].matches("[0-9]+")) {
sum = sum + Integer.parseInt(new StringBuffer(split[i]).reverse().toString());
}
}
System.out.println(sum);
Explanation:
Here we use regex to check if the String split contains only
digits.
Now we reverse the String and then parse it to an int before
summing.

Try this and works for any input in the form "We have x guests in room y". For your program however, instead if the for loop > 0 do > -1 I think:
Scanner scan = new Scanner(System.in);
scan.next(); scan.next();
String numberOne = "" + scan.nextInt();
scan.next(); scan.next(); scan.next();
String numberTwo = "" + scan.nextInt();
// String numberOne = "" + scan.nextInt(), numberTwo = "" + scan.nextInt();
String numberOneReversed = "", numberTwoReversed = "";
for(int k = numberOne.length() - 1; k > -1; k--)
numberOneReversed += numberOne.charAt(k);
for(int k = numberTwo.length() - 1; k > -1; k--)
numberTwoReversed += numberTwo.charAt(k);
int sum = Integer.parseInt(numberOneReversed) + Integer.parseInt(numberTwoReversed);
System.out.println("" + numberOneReversed + " + " + numberTwoReversed + " = " + sum);
scan.close();
Note for your program as defined in your question:
for (int i = a.length() - 1; i > -1; i--) {
instead of
for (int i = a.length() - 1; i > 0; i--) {
and
if (i != 0 && !Character.isDigit(a.charAt(i - 1))) {
instead of
for (int i = a.length() - 1; i > 0; i--) {
Will return the sum correctly.

Okay here is what I created using BigIntegers instead of ints:
public static BigInteger nameOfFunctionGoesHere(String input) {
BigInteger total = new BigInteger(new byte[] {0});
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total.add(new BigInteger(new String(flipped)));
i = j;
} else {
i++;
}
}
return total;
}
You can of course use ints as well like this:
public static int nameOfFunctionGoesHere(String input) {
int total = 0;
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total + Integer.parseInt(new String(flipped));
i = j;
} else {
i++;
}
}
return total;
}
With longs too:
public static long nameOfFunctionGoesHere(String input) {
long total = 0;
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total + Long.parseLong(new String(flipped));
i = j;
} else {
i++;
}
}
return total;
}

Related

How can I test credit numbers with hyphens (" -" ) to get it as INVALID . When I tried 4003-6000-0000-0014 i am getting errors

I cant get credit card numbers containing hymens as INVALID such as 4003-6000-0000-0014 must give me INVALID but its giving me errors of string.
public class prog {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in) ;
System.out.println("How many credit card you want to check?");
int numOfCredit = userInput.nextInt() ;
int creditnumbers[] = new int[numOfCredit] ;
for (int i = 0 ; i<numOfCredit ; i++)
{
System.out.println("Enter credit card number "+(i+1)+": ") ;
String creditNumber = userInput.next() ;
validateCreditCardNumber(creditNumber);
}
}
private static void validateCreditCardNumber(String str) { // function to check credit numbers
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++)
{
sum += ints[i];
}
if (sum % 10 == 0)
{
System.out.println("VALID");
}
else
{
System.out.println("INVALID");
}
}
}
I get these errors after running with hymens :
Exception in thread "main" java.lang.NumberFormatException: For input string: "-"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:642)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at testing/testing.prog.validateCreditCardNumber(prog.java:33)
at testing/testing.prog.main(prog.java:22)
you can replace in your string "-" with "" (blank) and then apply this function:
String card = "4003-6000-0000-0014";
Boolean t = check(card.replace("-",""));
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);
}

Next greatest number

I'm trying to find the next greatest number from the user input.If the user gives 23 it shows the output as 32.If there is number greater number then it has to print the same given number.But if the user gives 03 it shows 3 but it has to show 30.Because it takes 03 as octal number.How can i change the code to show the correct output as 30?
public class Main
{
static void swap(char ar[], int i, int j)
{
char temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num = in .nextInt();
char[] chars = ("" + num).toCharArray();
int i;
int n = chars.length;
for (i = n - 1; i > 0; i--)
{
if (chars[i] > chars[i - 1])
break;
}
if (i == 0)
System.out.println(num);
else {
int x = chars[i - 1], min = i;
for (int j = i + 1; j<n; j++)
{
if (chars[j] > x && chars[j]<chars[min])
min = j;
}
swap(chars, i - 1, min);
Arrays.sort(chars, i, n);
for (i = 0; i<n; i++)
System.out.print(chars[i]);
}
}
}
package com.demo;
import java.util.Arrays;
import java.util.Scanner;
public class Demo {
static void swap(char ar[], int i, int j)
{
char temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
//int num = in .nextInt();
char[] chars=null;
String numStr=in.next();
int num= Integer.valueOf(numStr);
if(numStr.startsWith("0")) {
chars= ("0" + num).toCharArray();
}else {
chars= ("" + num).toCharArray();
}
int i;
int n = chars.length;
for (i = n - 1; i > 0; i--)
{
if (chars[i] > chars[i - 1])
break;
}
if (i == 0)
System.out.println(num);
else {
int x = chars[i - 1], min = i;
for (int j = i + 1; j<n; j++)
{
if (chars[j] > x && chars[j]<chars[min])
min = j;
}
swap(chars, i - 1, min);
Arrays.sort(chars, i, n);
for (i = 0; i<n; i++)
System.out.print(chars[i]);
}
}
}
public static int findNextGreatestNumber(int[] arr, int k) {
int delta = Integer.MAX_VALUE;
int res = 0;
for (int a : arr) {
if (a - k > 0 && a - k < delta) {
delta = a - k;
res = a;
}
}
return delta == Integer.MAX_VALUE ? k : res;
}
You are reading the numbers from standard input as integers. Try reading them as strings instead:
Scanner in = new Scanner(System.in);
String num = in.nextLine();
char[] chars = num.toCharArray();
In your main(),take the input as String only, instead of taking it as integer.
String num=in.next();

How to increment integer Array values?

I am designing a problem in which I have to use an int array to add or subtract values. For example instead of changing 100 to 101 by adding 1, I want to do the same thing using the int array. It work like this:
int[] val = new int[3];
val[0] = 1;
val[1] = 0;
val[2] = 0;
val[2] += 1;
so, If I have to get a value of 101, I will add 1 to val[2].
The only problem I have is finding a way to make int array work like how adding and subtracting from an ordinary integer data set works.
Is this possible using a for loop or a while loop?
Any help will be appreciated!
Here's your homework:
public static int[] increment(int[] val) {
for (int i = val.length - 1; i >= 0; i--) {
if (++val[i] < 10)
return val;
val[i] = 0;
}
val = new int[val.length + 1];
val[0] = 1;
return val;
}
Make sure you understand how and why it works before submitting it as your own work.
Solution of this problem is designed by using String
You can refer to this method which will return sum of 2 nos having input in String format.
Input String should contain only digits.
class Demo {
public static String add(String a1, String b1) {
int[] a = String_to_int_Array(a1);
int[] b = String_to_int_Array(b1);
int l = a.length - 1;
int m = b.length - 1;
int sum = 0;
int carry = 0;
int rem = 0;
String temp = "";
if (a.length > b.length) {
while (m >= 0) {
sum = a[l] + b[m] + carry;
carry = sum / 10;
rem = sum % 10;
temp = rem + temp;
m--;
l--;
}
while (l >= 0) {
sum = a[l] + carry;
carry = sum / 10;
rem = sum % 10;
temp = rem + temp;
l--;
}
if (carry > 0) {
temp = carry + temp;
}
} else {
while (l >= 0) {
sum = a[l] + b[m] + carry;
carry = sum / 10;
rem = sum % 10;
temp = rem + temp;
m--;
l--;
}
while (m >= 0) {
sum = b[m] + carry;
carry = sum / 10;
rem = sum % 10;
temp = rem + temp;
m--;
}
if (carry > 0) {
temp = carry + temp;
}
}
return temp;
}
public static int[] String_to_int_Array(String s) {
int arr[] = new int[s.length()], i;
for (i = 0; i < s.length(); i++)
arr[i] = Character.digit(s.charAt(i), 10);
return arr;
}
public static void main(String a[]) {
System.out.println(add("222", "111"));
}
}
Quick & dirty:
static void increment(int[] array){
int i = array.length-1;
do{
array[i]=(array[i]+1)%10;
}while(array[i--]==0 && i>=0);
}
Note the overflow when incementing e.g. {9, 9}. Result is {0, 0} here.
public static void increment() {
int[] acc = {9,9,9,9};
String s="";
for (int i = 0; i < acc.length; i++)
s += (acc[i] + "");
int i = Integer.parseInt(s);
i++;
System.out.println("\n"+i);
String temp = Integer.toString(i);
int[] newGuess = new int[temp.length()];
for (i = 0; i < temp.length(); i++)
{
newGuess[i] = temp.charAt(i) - '0';
}
printNumbers(newGuess);
}
public static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}
If someone is looking for this solution using JavaScript or if you can translate it to java, here's your optimum solution:
function incrementArr(arr) {
let toBeIncrementedFlag = 1, // carry over logic
i = arr.length - 1;
while (toBeIncrementedFlag) {
if (arr[i] === 9) {
arr[i] = 0; // setting the digit as 0 and using carry over
toBeIncrementedFlag = 1;
} else {
toBeIncrementedFlag = 0;
arr[i] += 1;
break; // Breaking loop once no carry over is left
}
if (i === 0) { // handling case of [9,9] [9,9,9] and so on
arr.unshift(1);
break;
}
i--; // going left to right because of carry over
}
return arr;
}

String index out of range (Repeating Sequence of digits)

I seem to be having a problem with my code which is to look for the repeating sequence of digits. I have converted(?) double to string because I get the error unreachable statement. (which I guess helps to looking for the reason why I get the error I have now?).
Whenever I run it, it goes fine until I finish entering N and D.
It'll say "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3"
Here is my code below:
import java.util.*;
public class RepeatingSequence{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter N,D: ");
int numerator = in.nextInt();
int denominator = in.nextInt();
double quotient = numerator / denominator;
String number = "" + quotient;
char n = number.charAt(0);
int j = 1;
int z = 0;
String output = "";
char[] index = number.toCharArray();
for ( int i = 2; number.charAt(j) != number.charAt(i); i++ ){
index[z] = number.charAt(z);
index[j] = number.charAt(j);
index[i] = number.charAt(i);
output = output + index[i];
if ( index[i] != index[z] ){
System.out.print(index[z] + ".(" + index[j] + output + ")");
}
}
}
}
just add i < number.length() to the condition
( int i = 2; i < number.length() && number.charAt(j) != number.charAt(i); i++ )
For your exception, I think you should write safer code - something on the lines of:
int len = number.length();
for ( int i = 2; (i < len) && (j < len) &&
number.charAt(j) != number.charAt(i); i++ ){
...
}
I am not attempting to solve the problem that you are trying to solve but just the problem you are facing. Sorry for that.
I changed your code a little bit try it out and see what you think:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter N,D: ");
double numerator = in.nextDouble();
double denominator = in.nextDouble();
double quotient = numerator / denominator;
String number = "" + quotient;
char n = number.charAt(0);
int j = 1;
int z = 0;
String output = "";
char[] index = number.toCharArray();
int max = -1;
int currentNumber = -1;
int temp = -1;
int tempMax = -1;
System.out.println("" + quotient);
boolean check = true;
for(int i = (number.indexOf(".") + 1); i < index.length; i++)
{
if(max == -1)
{
currentNumber = i;
temp = i;
max = 1;
tempMax = 1;
}
else
{
if(index[i] == index[i-1])
{
tempMax++;
}
else
{
if(tempMax > max)
{
check = false;
max = tempMax;
currentNumber = temp;
}
tempMax = 1;
temp = i;
}
}
}
if(check)
{
max = tempMax;
}
System.out.println(index[currentNumber] + " repeats " + max + " times.");
}
Example of input/output:
Enter N,D: 1
3
0.3333333333333333
3 repeats 16 times.

incorrect logic in checksum function

public class CreditCardNumber {
private String issuerID = "000000";
private String accountNum = "999999999";
private int checkDigit = 0;
public CreditCardNumber(String TempissuerID, String TempaccountNum) {
if (TempissuerID != null && TempaccountNum != null
&& TempissuerID.length() == 6 && TempaccountNum.length() == 9)
if (Digits(TempissuerID) && Digits(TempaccountNum)) {
issuerID = TempissuerID;
accountNum = TempaccountNum;
calcCheckDigits();
}
}
public boolean Digits(String temp1) {
String temp = "0123456789";
int count = 0;
for (int i = 0; i < temp1.length(); i++)
for (int j = 0; j < temp.length(); j++)
if (temp1.charAt(i) == temp.charAt(j)) {
count++;
}
if (count == temp1.length()) {
return true;
}
return false;
}
public CreditCardNumber() {
}
public String getID() {
return issuerID;
}
public String getAccNum() {
return accountNum;
}
public int getDigits() {
return checkDigit;
}
private void calcCheckDigits() {
int sum;
sum = checkSum();
if ((sum + checkDigit) % 10 != 0) {
checkDigit = sum - (sum % 10);
}
System.out.printf("%d", checkDigit);
}
public void CreateCred(String TempissuerID) {
if (TempissuerID != null && TempissuerID.length() == 6
&& Digits(TempissuerID)) {
issuerID = TempissuerID;
} else {
issuerID = "000000";
}
StringBuilder TempString = new StringBuilder();
for (int i = 0; i < 9; i++) {
TempString = TempString.append((Math.random() * (9 - 0 + 1) + 0));
}
accountNum = TempString.toString();
calcCheckDigits();
}
private int checkSum() {
StringBuilder temp = new StringBuilder();
int num;
int sum = 0;
for(int i = 0 ; i <issuerID.length();i++)
{
temp = temp.append(issuerID.charAt(i));
}
for(int j = 0 ; j < accountNum.length(); j++)
{
temp = temp.append(accountNum.charAt(j));
}
System.out.println(temp);
for (int k = 0; k < temp.length(); k += 2) {
num = temp.charAt(k) - '0';
num *= 2;
if (num > 9)
num = 1 + (num % 10);
temp.setCharAt(k, (char) num);
}
for (int v = 0; v < temp.length(); v++) {
sum += temp.charAt(v) - '0';
}
System.out.printf("%d", sum);
return sum;
}
public String toString() {
String s = "";
String str = issuerID + accountNum;
return str;
}
}
I have a problem in my checksum method, I wrote some printf statement to check for the value of sum which turn out to be -930 but This is not what the value sum suppose to be , if adding only there is no reason for it to have a negative sign.I am expecting the checkDigit number to be 9 when I enter 321321 for issuerID and 654654654 for accountNum, and the value of sum in check sum will be passed to the calCheckDigits method to get the value for CheckDigit which is 9.
What am I doing wrong in this method?
ok I just edit the code now I get -30 for the sum
I just edit again my first 2 for loops in checksum was wrong leading my temp string value to be incorrect
now it get -320
still incorrect but getting better

Categories