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"));
}
}
Related
I am working on strings and working on a problem. The problem statement is to "add one to all digits inside string".I am not getting desired output for input numbers 129 and 9923.
can anyone please help!
import java.util.*;
public class Increment {
public static void main(String[] args) {
String number = "129";
int len = number.length();
int i = 0;
int temp = 0;
int before = 0;
int carry = 0;
String result = number;
for (i = len - 1; i >= 0; i--) {
temp = Integer.parseInt(number.charAt(i) + "");
if (temp >= 0 && temp < 9) {
carry = 0;
temp = temp + 1;
result = result.replace(number.charAt(i), (char)(temp + '0'));
} else {
carry = 1;
if (i != 0) {
before = Integer.parseInt(number.charAt(i - 1) + "");
before = before + 1;
result = result.replace(number.charAt(i), '0');
result = result.replace(number.charAt(i - 1), (char)(before + carry));
i = i - 1;
} else {
result = result.replace(number.charAt(i), '0');
result = "1" + result;
}
}
}
System.out.println(result);
}
}
You define a method for adding two strings and call that method
public static String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int i = num1.length() - 1, j = num2.length() - 1;
int carry = 0, sum = 0;
while (i >= 0 || j >= 0) {
sum = carry;
if (i >= 0) sum += num1.charAt(i) - '0';
if (j >= 0) sum += num2.charAt(j) - '0';
sb.append(sum % 10);
carry = sum / 10;
i--;
j--;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
, main
public static void main(String[] args) {
String num1 = "129";
String num2 = "9923";
String res1 = addStrings(num1, "1".repeat(num1.length()));
String res2 = addStrings(num2, "1".repeat(num2.length()));
System.out.println(res1);
System.out.println(res2);
}
, output
240
11034
I would use regex, it makes it a much simpler solution:
public static void main(String[] args) {
String text = "text240 moretext 350 evenmore460text";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String value = matcher.group();
int val = Integer.parseInt(value) + 1;
text = text.replace(value, Integer.toString(val));
}
System.out.println(text);
}
The problem is this line of code, check here for more info
result = result.replace(number.charAt(i - 1), (char) (before + carry));
You may change it like below, but that would replace all occurrences of first argument as #user16320675 points out
result = result.replace(number.charAt(i - 1), Character.forDigit(before + carry, 10));
So, I would suggest to use StringBuilder instead of String in order to take advantage of the setCharAt(int idx, char c) method
For a given positive integer N of not more than 1000000 digits, write the value of the smallest palindrome larger than N to output.
Here is my code:
public class Palin {
public static String reverseString(String s) {
String newS = "";
for(int i = s.length() - 1; i >= 0; i--)
newS += s.charAt(i);
return newS;
}
public static String getPalin(String s) {
int lth = s.length();
String left = "", mid = "", right = "", newS = "";
if(lth % 2 != 0) {
left = s.substring(0, lth / 2);
mid = s.substring(lth / 2, lth / 2 + 1);
right = reverseString(left);
newS = left + mid + right;
if(s.compareTo(newS) < 0) return newS;
else {
int temp = Integer.parseInt(mid);
temp++;
mid = Integer.toString(temp);
newS = left + mid + right;
return newS;
}
}
else {
left = s.substring(0, lth / 2 - 1);
mid = s.substring(lth / 2 - 1, lth / 2);
right = reverseString(left);
newS = left + mid + mid + right;
if(s.compareTo(newS) < 0) return newS;
else {
int temp = Integer.parseInt(mid);
temp++;
mid = Integer.toString(temp);
newS = left + mid + mid + right;
return newS;
}
}
}
public static void main(String[] args) throws java.lang.Exception {
Scanner input = new Scanner(System.in);
//Scanner input = new Scanner(System.in);
int k = input.nextInt();
String[] s = new String[k];
for(int i = 0; i < k; i++) {
s[i] = input.next();
}
for(int i = 0; i < k; i++) {
System.out.println(getPalin(s[i]));
}
}
}
My idea is use a String represent for a number. I divide this String into 2 part, coppy first part and reverse it for second part. I think my solve is correct but it not fast enough. I need a more efficient algorithm.
Thanks
EDITED
Since you said that:
For a given positive integer N of not more than 1000000 digits
My previous solution won't work since I have converted them to int and an int can't accommodate 1000000 digits. Thus I have made a new approach, an approach that doesn't need any String to int conversion.
Refer to the code and comment below for details.
CODE:
package main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Scanner input = new Scanner(System.in);
int k = Integer.parseInt(input.nextLine());
String[] s = new String[k];
for (int i = 0; i < k; i++) {
s[i] = input.nextLine();
}
for (int i = 0; i < k; i++) {
System.out.println(getPalin(s[i]));
}
input.close();
}
public static String getPalin(String s) {
// initialize the result to "" since if input is 1 digit, nothing is printed
String result = "";
// if input is greater than 1000000 digits
if (s.length() >= 1000000) {
// return the highest palindrome less than 1000000
result = "999999";
} else if (s.length() > 1) {
// get the middle index of the string
int mid = s.length() % 2 == 0 ? s.length() / 2 : (s.length() / 2) + 1;
// get the left part of the string
String leftPart = getPalindrome(s.substring(0, mid));
if (s.length() % 2 == 0) {
// attach the left part and the reverse left part
result = leftPart + new StringBuilder(leftPart).reverse().toString();
} else {
// attach the left part and the reverse left part excluding the middle digit
result = leftPart
+ new StringBuilder(leftPart.substring(0, leftPart.length() - 1)).reverse().toString();
}
// check if the new result greater than 1000000 digits
if (result.length() >= 1000000) {
// return the highest palindrome less than 1000000
result = "999999";
}
}
return result;
}
public static String getPalindrome(String param) {
String result = "";
// iterate through the string from last index until index 0
for (int i = param.length() - 1; i >= 0; i--) {
// get the char at index i
char c = param.charAt(i);
/*
* increment char since the next palindrome is the current digit + 1. Example:
* User input is 121, then param will be 12 so the next is 13
*/
c++;
/*
* check if the current character is greater than '9', which means it is not a
* digit after incrementing
*/
if (c > '9') {
// set the current char to 0
c = '0';
// check if index is at index 0
if (i - 1 < 0) {
// if at index 0 then add '1' at start
result = '1' + result;
} else {
// if not then append c at result
result = result + c;
}
} else {
// check if index is at index 0
if (i - 1 < 0) {
// if not then prepend c at result
result = c + result;
} else {
// if not then get the rest of param then append c and result
result = param.substring(0, i) + c + result;
}
break;
}
}
return result;
}
}
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.
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);
}
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;
}