Adding two numbers of large length using strings [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I can't seem to figure out what wrong with this method used to add two strings. It has a buffer when stores each added digit and finally displays. However when two huge numbers (greater than 10 digits) are added it just truncates and doesn't store the remainder of the string.
public static void add(String a,String b){
StringBuilder buf = new StringBuilder();
if((a.length() - 1==0)&&(a.charAt(0)=='0')){
System.out.println(b);
return;
}
if((b.length() - 1==0)&&(b.charAt(0)=='0')){
System.out.println(a);
return;
}
else{
for ( int i1 = a.length() - 1, i2 = b.length() - 1, carry = 0;
(i1 >= 0 && i2 >= 0) || carry != 0;i1--, i2-- ) {
int digit1 = i1 < 0 ? 0 :
Integer.parseInt(Character.toString(a.charAt(i1)));
int digit2 = i2 < 0 ? 0 :
Integer.parseInt(Character.toString(b.charAt(i2)));
int digit = digit1 + digit2 + carry;
if (digit > 9) {
carry = 1;
digit -= 10;
} else {
carry = 0;
}
buf.append(digit);
}
}
System.out.println(buf.reverse().toString());
}

Since need to stop when both i1 and i2 reach a negative value, the condition should be
i1 >= 0 || i2 >= 0 || carry != 0
rather than
(i1 >= 0 && i2 >= 0) || carry != 0
Demo on ideone.

Just use BigInteger, and your whole method is then three lines long.

Related

How can I count integer occurrence when the int is 0 in java? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm a beginner in java and I made a program to count the number of times an int d occurs in a given integer n i.e n = 988, d = 8 returns 2.
It works with most cases (negative, positive, etc.) but my code says n = 0, d = 1 contains 1, which is wrong. How do I add a place to my 0 without making the integer 10 (which I erroneously do in my first if statement).
public class countingints{
public static int count(int n, int d) {
n = Math.abs(n);
if(n == 0) {
n = 10;
}
int result = 0;
while (n > 0) {
int place = n % 10;
if (place == d) {
result++;
}
n /= 10;
}
return result;
}
public static void main(String[] args) {
System.out.println(count(0, 1)); //SHOULD return 0
System.out.println(count(0, 5)); //returns 0
}
}
if(n == 0) {
n = 10;
}
```
Computer just follows instructions. If n is 0, n is set to 10, and 10 contains a single 1 digit.
If perhaps your intent with this if (n == 0) n = 10 line is to ensure that e.g. count(0, 0) returns 1, then just code that in: if (n == 0 && d == 0) return 1; - that's a weird case because mathematically speaking the question 'how many times does the digit 0 show up' is tricky. You can write 15 as 0015 as well, and in many ways, 0 is just a way of writing it, the number really can be considered just a completely blank string with no digits at all.
Point is, it's logical, more or less, that your algorithm does 'weird things' when you ask it for how many zeroes are in a number, in particular when you ask it how many zeroes are in the number 0. "Weird cases" usually mean they need hardcoding, so, do that.

Exception in thread “main” java.lang.ArithmeticException: / by zero [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
My program is supposed to print all numbers from 1111-9999 where all numbers are evenly divisible by n. However, I am getting an exception stating that I'm dividing by zero. Why is this?
package NestedLoops;
import java.util.Scanner;
public class SpecialNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
for (int i = 1111; i < 9999; i++) {
int firstdigit = i % 10;
int seconddigit = (i / 10) % 10;
int thirddigit = (i / 100) % 10;
int fourtdigit = i / 1000;
if ((n % firstdigit == 0)&& (n % seconddigit == 0) && (n % thirddigit == 0) && (n %
fourtdigit == 0)) {
System.out.printf("%d ", i);
}
}
}
}
enter image description here
This is happens because the % operator are using dividing to calculate the result, so anyNumber % 0 will throw an java.lang.ArithmeticException: / by zero.
To prevent this, check if your digits are equal to 0 before the if statement.

Why 1534236469 can't pass [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I think 1534236469 out of range! Leetcode: 7. Reverse Integer
I can't pass the test input 1534236469. why? the return range is[Integer.MAX_VALUE, Integer.MIN_VALUE],others should return zero
class Solution {
public int reverse(int x) {
if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE)
return 0;
int ans = 0;
while(x != 0) {
ans = ans * 10 + (x % 10);
x /= 10;
}
return ans;
}
}
Thank for your help
The reverse of 1534236469 is 9646324351, which is larger than Integer.MAX_VALUE, so your code will result in numeric overflow and an incorrect result.
You can use long instead of int to fix the problem.
EDIT:
Your added if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) condition is pointless, since x is int, so it will never be outside the valid range of ints.
Even if x is within the valid range, the reverse of x may be outside the range. If you want to detect that the reversed x is too large and return 0, you should use long internally:
class Solution {
public int reverse(int x) {
long ans = 0;
while(x != 0) {
ans = ans * 10 + (x % 10);
x /= 10;
}
if(ans > Integer.MAX_VALUE || ans < Integer.MIN_VALUE) {
return 0;
} else {
return (int) ans;
}
}
}

Incremented by a value x but it gets incremented by value x-1

I am implementing an Algorithm where when user gives input string, every character in string (if it is alphabet) should be incremented by value given(here rotator). I am playing with this code for 2 hr but can't figure out why when i increment by value rotator, it gets incremented by rotator-1.
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
int length = in.nextInt();
String input = in.next();
int nextvalue = 0;
int temp = 0;
char array[] = input.toCharArray();
int rotator = in.nextInt();
for(int i = 0; i < length; i++){
if((array[i] >= 'a' && array[i] <= 'z') || (array[i] >= 'A' && array[i] <= 'Z')){
nextvalue = (int)array[i] + rotator;
array[i] = (char)nextvalue;
if((int)array[i] > (int)'z'){
temp = (int)array[i] - (int)'z';
nextvalue = (int)'a' + temp -1;
array[i] = (char)nextvalue;
}
else if((int)array[i] > (int)'Z'){
temp = (int)array[i] - (int)'Z';
nextvalue = (int)'Z' + temp -1;
array[i] = (char)nextvalue;
}
}
}
System.out.println(array);
}
}
Inside first if there are two if statements to handle(Overflow condition) if letter is > z or >Z. Now if I Remove those two statements everything except overflow condition is correctly printed
(without overflow condition)
Sample I/P :
11 <- String length
middle-Outz
2 <- rotator
Sample O/P :
okffng-Qwv| <- Overflow condition not handled
(with overflow condition)
Sample I/P :
11
middle-Outz
2
Sample O/P :
njeemf-Qvub <- Overflow handled but everything else incremented by rotator - 1 except 'Q'
Why is this happening? I also checked using print statement in inner if condition , it executes only one time for this input since there is only one overflow condition.
Help/Suggestion appreciated.Thanks.
I think the easiest way to handle the overflow cases is to use the modulus operator to let the character wrap-around any number of times to land in the current logical position. Something like this should work:
for (int i=0; i < length; i++) {
if (array[i] >= 'a' && array[i] <= 'z') {
int currDiff = (int)array[i] - (int)'a';
int newPos = (int)'a' + ((rotator + currDiff) % 26);
array[i] = (char)newPos;
}
else if (array[i] >= 'A' && array[i] <= 'Z') {
int currDiff = (int)array[i] - (int)'A';
int newPos = (int)'A' + ((rotator + currDiff) % 26);
array[i] = (char)newPos;
}
}
I tested this code using an input string of abcdefg and a rotator value of 51, which returned zabcdef. This is expected, because we rotated one step short of two complete rounds. Hence, the a landed on z, after one complete rotation, and the following characters followed suit.
Note that there is a much nicer way of handling the calculus of character positions here, but this answer stays true to the way you were doing it in your original question.
Final note:
The modulus operator % returns the remainder of the division of the number which preceeds it and proceeds it. In the solution I gave above, I take the effective rotator % 26. Here, the effective rotator is the current distance of the letter from either a or A plus however many steps we want to rotate. By taking this number mod 26, we always will end up with a number between 0 and 25. Hence, we will always take between 0 and 25 steps from a or A, which is the behavior you want in your program.
Because you are modifying it twice in your loop.
for(int i = 0; i < length; i++){
if((array[i] >= 'a' && array[i] <= 'z') || (array[i] >= 'A' && array[i] <= 'Z')){
nextvalue = (int)array[i] + rotator;
array[i] = (char)nextvalue; //<-- modifies from m to o
if((int)array[i] > (int)'z'){
temp = (int)array[i] - (int)'z';
nextvalue = (int)'a' + temp -1;
array[i] = (char)nextvalue;
}
else if((int)array[i] > (int)'Z'){
temp = (int)array[i] - (int)'Z';
nextvalue = (int)'Z' + temp -1;
array[i] = (char)nextvalue; //<--modifies again from o to n
}
}
}
The mistake is in this line:
if ((int) array[i] > (int) 'Z') {
You have to keep in mind that lowercase letters come "after" uppercase letters: 'Z' is represented by 90, and (for example) 'j ' is represented by 106 (for more info see this). The reason why 'Q' isn't affected by this mistake is because it is also a capital letter, and thus has a smaller decimal representation than 'Z'.
To fix this, you have to replace the line of code above with something along the lines of this:
if ((int) array[i] > (int) 'Z' && (int) array[i] <= (int) 'Z' + rotator) {
Instead of
nextvalue = (int)'Z' + temp -1;
Shouldn't it be
nextvalue = (int)'A' + temp -1;

How to check values in a string?

So i have a string in military time format : "1532" corresponding to 3:32pm.
I'm trying to write a method to check if each digit in time string is an appropriate digit. So the first element cannot be greater than 2 or equal to 0, and so forth. Currently, my code doesn't run past the second log statement and I'm hoping you guys could help!
cheers!
String mOpen = "1532";
Log.d("hoursTesting","pass1, length is > 2");
if(mOpen.getText().length() == 4)
{
Log.d("hoursTesting","pass2, length is == 4");
char[] tempString = mOpen.getText().toString().toCharArray();
if(tempString[0] != 0 && tempString[0] < 3)
{
Log.d("hoursTesting","pass3, first index is != 0 and < 3");
if(tempString[0] == 1)
{
Log.d("hoursTesting","pass4, first index is 1");
if(tempString[2] <= 5)
{
Log.d("hoursTesting","pass5, third index is <= 5, success!");
}
}
else //tempString[0] is equal to 2
{
Log.d("hoursTesting","pass4, first index is 2");
if(tempString[1] < 4)
{
Log.d("hoursTesting","pass5, second index is <3");
if(tempString[2] <= 5)
{
Log.d("hoursTesting","pass6, third index is <= 5, success!");
}
}
}
}
}
tempString contains characters, not numbers.
i.e. '0' not 0 etc.
Easiest fix is to compare characters e.g. tempString[0] == '1' Alternatively, you can do something like int digit1 = tempString[0] - '0'; - but that kind of assumes you already know you just have digits in the string.
Note that cos of those clever ASCII guys and their tricky character set '0' < '1' < '2' etc, so you can still say if (str[0] < '2') etc. You just need to be a bit careful that you are only dealing with digits.
Personally I'd convert the first 2 chars to a number and the second 2 chars to a number and then just check 0 <= number1 <= 23 and 0 <= number2 <= 59.
You are comparing char with int here:
if(tempString[0] != 0 && tempString[0] < 3)
It should work like this:
if(tempString[0] != '0' && tempString[0] < '3')
I would substring the hours and minutes components and then check to see if each one be in range:
public boolean isTimeValid(String mOpen) {
int hours = Integer.parseInt(mOpen.substring(0, 2));
int minutes = Integer.parseInt(mOpen.substring(2));
if ((hours >= 0 && hours <= 24) && (minutes >= 0 && minutes <= 59)) {
return true;
}
else {
return false;
}
}

Categories

Resources