Error in float to string conversion - java

Given a float number 7.64, convert it into the string WITHOUT using any inbuilt function/library.
This problem is easy in java . As + operator is overloaded for strings .We can do
class Float2String
{
public static void main(String[] args)
{
float f=7.64f;
String result;
result=""+f;
System.out.println(result);
}
}
But in c as i try to do so ..
int main()
{
float f =2.44;
int i, j = 0;
i = (int) f;
f = f - i;
while(f > 0) {
f *= 10;
j = (j*10) + (int) f;
f = f - (int) f;
}
//now make itoa() to convert i and j to strings .
return 0;
}
Here problem is that floating point error begin to sneak into as while loop goes and j is left with incorrect decimal part .
for example in above case value of f varies like
So how to do this problem in c or C++ .

The sudden jump to an entirely wrong value is caused by j overflowing its int. You could use an unsigned long.
Thel loop will probably not reach 0 however, due to the fact, that floating point numbers are just an approximations of a sum of (negative) powers of 2. Such sums will not decrease when multiplying by 10 and then subtracting the integer part.
The best way would be having a fixed number of digits, multiplying with 10n and then chopping trailing zeroes.

The solution is to print f with the precision (=number of digits) supported by float.
int main()
{
float f =2.44;
int i, len;
char str[100];
i = (int) f;
itoa(i, str, 10);
len = strlen(str);
str[len] = '.';
f = f - i;
while(len <= 6) {
len++;
f *= 10;
str[len] = '0' + (int)f;
f = f - (int) f;
}
str[len + 1] = '\0';
/* Remove trailing zeroes and decimal points. */
for (;len > 0 && (str[len] == '0' || str[len] == '.'); --len) {
if (str[len] == '.') {
str[len] = '\0';
break;
}
str[len] = '\0';
}
printf("%s", str);
return 0;
}

Apart from specifying the number of decimal places, the other way to calculate the decimal value taking into account floating point inaccuracies is to use FLT_EPSILON (or DBL_EPSILON) defined in float.h.
FLT_EPSILON is the difference between 1.0 and the minimum float value greater than 1.0
#include<stdio.h>
#include<float.h>
int main()
{
float origf = 2.44;
float f = origf, newf = 0.0;
int i, j = 0;
int powerOfTen = 1;
i = (int) f;
f = f - i;
do
{
f *= 10;
powerOfTen *= 10;
j = j * 10 + (int)f;
f = f - (int) f;
newf = i + (float)j/ powerOfTen;
} while ((origf + FLT_EPSILON) > newf && newf > (origf - FLT_EPSILON));
printf("%d %d\n", i, j);
return 0;
}

Related

Find a pair of natural numbers who have the least energy among all pairs having sum of n

There is a natural number n. You have to find a pair of natural numbers x, y whose sum is n and also have the least energy among other pair having the sum n.
Energy(x) = sum of all digits of x
Total Energy = Energy(x) + Energy(y)
1 <= n <= 10^9
For eg,
n = 10000
A few pairs:
5000 + 5000 -> Energy = 10
1000 + 9000 -> Energy = 10
9999 + 1 -> Energy = 37
2999 + 7001 -> Energy = 37
So possible answers are:
(5000, 5000), (1000, 9000) etc
I have tried the solution noted above so far but it is not an optimized approach
I will loop from 1 to n-1 and and try all pairs and check their sum of digits but it will take too much time for big numbers.
e.g.
n= 50
1,49--> energy 14
2,48--> energy 14
3,47--> energy 14
4,46--> energy 14
5,45--> energy 14
.
.
.
.
10,40-->energy 5
(Edited) After some thought, I arrived at the following solution. Would appreciate if somebody can come up with a better solution
public int sum(int n) {
String s = String.valueOf(n);
if (isNonZeroOnlyOne(n)) {
int num = getNonZeroNo(n);
if (num == 1)
return 10;
return num;
}
return calculateEnergy(s);
}
private int calculateEnergy(String s) {
int sum = 0;
for(int i=0; i<s.length(); i++)
sum += s.charAt(i) - '0';
return sum;
}
private int getNonZeroNo(int n) {
String s = String.valueOf(n);
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (c != '0')
return c-'0';
}
return '0';
}
private boolean isNonZeroOnlyOne(int n) {
String s = String.valueOf(n);
int count = 0;
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (c != '0')
count++;
if (count > 1)
return false;
}
return true;
}
It's simple.
if n is of type 10^x then the answer is 10. otherwise answer is the sum of digits of n.
The idea here is to break down the number into a pair containing digits less than that are present in n. if you break down into smaller digits then sum remains the same as the original number.
example for 7= 1-6,2-5,3-4.
for a number like 100, 1000....
digit 1 can't be broken down into further pairs, so we try to make 10 as the sum of digit so that the sum becomes n.
like for 10=5-5,2-8,3-7
100=20-80,40-60
for other numbers, like 123
it can be broken into 100-23, 120-3, 111-12... all will give you sum 6. which is the sum of digits of the original number.
if you try to break down into further pairs like 80-43, 52-71, you will see that the digit sum increases as you broken down to a number containing digits which is higher than those are present in n. like 8 4,5,7 are greater than 3.
The least energy can be derived by a simple formula.
1) Given N > 100, the pair can be N-100 and 100 , and the energy will be same as the energy of N.
eg : N = 500 ; Pair = 400 and 100 ; Energy = 5
2) N >=10 and N <=100 , pair = N-10 and 10
eg : N = 50 ; Pair = 40 and 10 ; Energy = 5
3) N >=2 and N <=10 , pair = N-1 and 1
eg : N = 5 ; Pair = 4 and 1 ; Energy = 5
I spent more than 1 hour on this problem. What should be answer for n = 1? So I think n should be greater than 1. I am assuming n > 1.
So brute-force solution won't work here because n is huge enough. So you need more optimized solution. You need to think think about how many times you have to carry 1 in the sum to make n. It is at most 9 times!
If you have some basic idea with digit-dp(Dynamic Programming) then this problem is easy. Try to place all possible digit on a place of n and take minimum energy among them. This problem is easy when you fully understand digit-dp technique. You can learn it from here and here.
For practice, you can find a lot of problems here (Dynamic programming section).
For your references, I wrote this code just now and it is working properly. Hope you can use this as a reference.
#include <bits/stdc++.h>
using namespace std;
const string INF_STRING = "9999999";
const int INF_INT = 9999999;
pair<string, int> INF = make_pair(INF_STRING, INF_INT);
int nod;
int digits[10];
int num_of_digits(int a) {
int cnt = 0;
while(a) {
digits[cnt] = a % 10;
a = a / 10;
cnt++;
}
return cnt;
}
pair<string, int> dp[10][2][2][2];
pair<string, int> solve(int ind, int carry, bool is1, bool is2) {
if(ind >= nod) {
if(carry != 0 || !is1 || !is2) return INF;
return make_pair("", 0);
}
pair<string, int> &ret = dp[ind][carry][is1][is2];
if(ret.second != -1) return ret;
ret = INF;
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
int s = (i + j + carry);
pair<string, int> cur = INF;
if(s % 10 == digits[ind]) {
cur = solve(ind + 1, s / 10, is1 || (i > 0? 1:0), is2 || (j > 0? 1:0));
}
if((cur.second + i + j) < ret.second) {
ret.second = cur.second + i + j;
ret.first = cur.first + (char)(i + '0');
}
}
}
return ret;
}
int stringToInt(string num) {
stringstream ss;
ss<<num;
int ret;
ss >> ret;
return ret;
}
int main() {
int i, t, cases = 1, j, k, pos;
int n;
scanf("%d", &n);
nod = num_of_digits(n);
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 2; j++) {
dp[i][j][0][0] = make_pair(INF_STRING, -1);
dp[i][j][0][1] = make_pair(INF_STRING, -1);
dp[i][j][1][0] = make_pair(INF_STRING, -1);
dp[i][j][1][1] = make_pair(INF_STRING, -1);
}
}
pair<string, int> res = solve(0, 0, 0, 0);
string num1_str = res.first;
int num1 = stringToInt(num1_str);
int num2 = n - num1;
printf("Minimum Energy: %d\n", res.second);
printf("Num1 = %d, Num2 = %d\n", num1, num2);
return 0;
}
/*
Input:
10000
Output:
Minimum energy: 10
Num1 = 1000, Num2 = 9000
*/
Here is the answer in javascript in simple way.
function calculateEnergy(n) {
let e = 0
while(n > 0) {
e += n % 10
n = Math.floor(n / 10)
}
return e
}
function countMinEnergy(n) {
let minE = n
let i = 1
while(i <= n/2) {
let e = calculateEnergy(i) + calculateEnergy(n - i)
minE = e < minE ? e : minE
i++
}
return minE
}
countMinEnergy(4325)
Here is scala solution
object LeastEnergyPair extends App {
private def getCountOfPair(array: Array[Int],sum: Int): mutable.Set[(Int, Int)] = {
val seen = mutable.Set[Int]()
val out = mutable.Set[(Int,Int)]()
array map { x =>
val target = sum - x
if (seen.contains(target) || target*2 == sum)
out += ((Math.min(x,target),Math.max(x,target)))
else
seen += x
}
println(out)
out
}
private def sum(i:Int): Int = i.toString.toCharArray.map(_.asDigit).sum
def findLeastEnergyPair(a: mutable.Set[(Int,Int)]): (Int,Int) = {
var min = Int.MaxValue
var minPair = (0,0)
a.foreach {
case (i,j) =>
if (sum(i) + sum(j) < min) {
min = sum(i) + sum(j)
minPair = (i,j)
println(s"$min ----- $minPair")
}
}
minPair
}
println(findLeastEnergyPair(getCountOfPair((1 to 10000).toArray, 10000)))
}
The below logic will cover all scenarios
if (N%10 == 0) {
x1= (N/10);
x2 = N-x1
}else{
x1 = N-10;
x2 = 10;
}

Java won't print output

I'm using binary search to write a simple square root calculator that takes in doubles in Java. When I tried to test my code by printing out the answer in the main function, however, nothing got printed out in the terminal. I also got errors Possible lossy conversion from double to float......
Here is my code:
public class MyMath{
public static double sqrt(double n){
double u = 1;
double l = 0;
float m = (u + l) / 2;
double norm_input = 1;
float acc = 0.00000000001;
double answer = 0;
if ((n > 0) && (n < 1)){
if ((m * m) < n){
l = m;
}else{
u = m;
}
answer = (u + l) / 2;
return answer;
}else{
int count = 0;
while (n > 1){
n = n / 4;
norm_input = norm_input * 2;
count++;
}
while ((u - l) > acc){
if ((m * m) < n){
l = m;
}else{
u = m;
}
}
answer = (u + l) / 2 * norm_input;
return answer;
}
}
public static void main(String[] args){
double a = new MyMath().sqrt(4);
System.out.println(a);
}
}
It is stuck in infinite loop in second while condition, that's the reason it is not printing values to console.
float m = (u + l) / 2;
Here you have to type cast into float because when two datatype variable participated in division the result would be in higher data type.
float acc = 0.00000000001;
Here also you have type cast because by default java treats a decimal point value as Double.
while ((u - l) > acc){
if ((m * m) < n){
l = m;
}
}
and your code here is going to infinite loop .

Adding numbers which are stored in string variables

Given two non-negative numbers num1 and num2 represented as strings, return the sum of num1 and num2.
The length of both num1 and num2 is less than 5100.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zeros.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
I tried my solution but it doesn't work. Suggestions?
public class Solution {
public String addStrings(String num1, String num2) {
double multiplier = Math.pow(10, num1.length() - 1);
int sum = 0;
for (int i = 0; i < num1.length(); i++){
sum += ((((int) num1.charAt(i)) - 48) * multiplier);
multiplier /= 10;
}
multiplier = Math.pow(10, num2.length() - 1);
for (int i = 0; i < num2.length(); i++){
sum += ((((int) num2.charAt(i)) - 48) * multiplier);
multiplier /= 10;
}
return "" + sum;
}
}
You must not use any built-in BigInteger library or convert the inputs to integer directly.
Note that you are adding two integers of up to 5100 digits each. That is not that max value, but the max number of digits.
An int (your sum variable) cannot hold values like that. BigInteger can, but you're not allowed to use it.
So, add the numbers like you would on paper: Add last digits, write lower digit of the sum as last digit of result, and carry-over a one if needed. Repeat for second-last digit, third-last digit, etc. until done.
Since the sum will be at least the number of digits of the longest input value, and may be one longer, you should allocate a char[] of length of longest input plus one. When done, construct final string using String(char[] value, int offset, int count), with an offset of 0 or 1 as needed.
The purpose of this question is to add the numbers in the string form. You should not try to convert the strings to integers. The description says the length of the numbers could be up to 5100 digits. So the numbers are simply too big to be stored in integers and doubles. For instance In the following line:
double multiplier = Math.pow(10, num1.length() - 1);
You are trying to store 10^5100 in a double. In IEEE 754 binary floating point standard a double can a store number from ±4.94065645841246544e-324 to ±1.79769313486231570e+308. So your number won't fit. It will instead turn into Infinity. Even if it fits in double it won't be exact and you will encounter some errors in your follow up calculations.
Because the question specifies not to use BigInteger or similar libraries you should try and implement string addition yourself.
This is pretty straightforward just implement the exact algorithm you follow when you add two numbers on paper.
Here is working example of adding two strings without using BigInteger using char array as intermediate container. The point why double can't be used has been explained on #Tempux answer. Here the logic is similar to how adding two numbers on paper works.
public String addStrings(String num1, String num2) {
int carry = 0;
int m = num1.length(), n = num2.length();
int len = m < n ? n : m;
char[] res = new char[len + 1]; // length is maxLen + 1 incase of carry in adding most significant digits
for(int i = 0; i <= len ; i++) {
int a = i < m ? (num1.charAt(m - i - 1) - '0') : 0;
int b = i < n ? (num2.charAt(n - i - 1) - '0') : 0;
res[len - i] = (char)((a + b + carry) % 10 + '0');
carry = (a + b + carry) / 10;
}
return res[0] == '0' ? new String(res, 1, len) : new String(res, 0, len + 1);
}
This snippet is relatively small and precise because here I didn't play with immutable String which is complicated/messy and yield larger code. Also one intuition is - there is no way of getting larger output than max(num1_length, num2_length) + 1 which makes the implementation simple.
You have to addition as you do on paper
you can't use BigInteger and the String Length is 5100, so you can not use int or long for addition.
You have to use simple addition as we do on paper.
class AddString
{
public static void main (String[] args) throws java.lang.Exception
{
String s1 = "98799932345";
String s2 = "99998783456";
//long n1 = Long.parseLong(s1);
//long n2 = Long.parseLong(s2);
System.out.println(addStrings(s1,s2));
//System.out.println(n1+n2);
}
public static String addStrings(String num1, String num2) {
StringBuilder ans = new StringBuilder("");
int n = num1.length();
int m = num2.length();
int carry = 0,sum;
int i, j;
for(i = n-1,j=m-1; i>=0&&j>=0;i--,j--){
int a = Integer.parseInt(""+num1.charAt(i));
int b = Integer.parseInt(""+num2.charAt(j));
//System.out.println(a+" "+b);
sum = carry + a + b;
ans.append(""+(sum%10));
carry = sum/10;
}
if(i>=0){
for(;i>=0;i--){
int a = Integer.parseInt(""+num1.charAt(i));
sum = carry + a;
ans.append(""+(sum%10));
carry = sum/10;
}
}
if(j>=0){
for(;j>=0;j--){
int a = Integer.parseInt(""+num2.charAt(j));
sum = carry + a;
ans.append(""+(sum%10));
carry = sum/10;
}
}
if(carry!=0)ans.append(""+carry);
return ans.reverse().toString();
}
}
You can run the above code and see it works in all cases, this could be written in more compact way, but that would have been difficult to understand for you.
Hope it helps!
you can use this one that is independent of Integer or BigInteger methods
public String addStrings(String num1, String num2) {
int l1 = num1.length();
int l2 = num2.length();
if(l1==0){
return num2;
}
if(l2==0){
return num1;
}
StringBuffer sb = new StringBuffer();
int minLen = Math.min(l1, l2);
int carry = 0;
for(int i=0;i<minLen;i++){
int ind = l1-i-1;
int c1 = num1.charAt(ind)-48;
ind = l2-i-1;
int c2 = num2.charAt(ind)-48;
int add = c1+c2+carry;
carry = add/10;
add = add%10;
sb.append(add);
}
String longer = null;
if(l1<l2){
longer = num2;
}
else if(l1>l2){
longer = num1;
}
if(longer!=null){
int l = longer.length();
for(int i=minLen;i<l;i++){
int c1 = longer.charAt(l-i-1)-48;
int add = c1+carry;
carry = add/10;
add = add%10;
sb.append(add);
}
}
return sb.reverse().toString();
}
The method takes two string inputs representing non-negative integers and returns the sum of the integers as a string. The algorithm works by iterating through the digits of the input strings from right to left, adding each digit and any carryover from the previous addition, and appending the resulting sum to a StringBuilder. Once both input strings have been fully processed, any remaining carryover is appended to the output string. Finally, the string is reversed to produce the correct output order.
Hope this will solve the issue.!
public string AddStrings(string num1, string num2)
{
int i = num1.Length - 1, j = num2.Length - 1, carry = 0;
StringBuilder sb = new StringBuilder();
while (i >= 0 || j >= 0 || carry != 0) {
int x = i >= 0 ? num1[i--] - '0' : 0;
int y = j >= 0 ? num2[j--] - '0' : 0;
int sum = x + y + carry;
sb.Append(sum % 10);
carry = sum / 10;
}
char[] chars = sb.ToString().ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
Previous solutions have excess code. This is all you need.
class ShortStringSolution {
static String add(String num1Str, String num2Str) {
return Long.toString(convert(num1Str) + convert(num2Str));
}
static long convert(String numStr) {
long num = 0;
for(int i = 0; i < numStr.length(); i++) {
num = num * 10 + (numStr.charAt(i) - '0');
}
return num;
}
}
class LongStringSolution {
static String add(String numStr1, String numStr2) {
StringBuilder result = new StringBuilder();
int i = numStr1.length() - 1, j = numStr2.length() - 1, carry = 0;
while(i >= 0 || j >= 0) {
if(i >= 0) {
carry += numStr1.charAt(i--) - '0';
}
if(j >= 0) {
carry += numStr2.charAt(j--) - '0';
}
if(carry > 9) {
result.append(carry - 10);
carry = 1;
} else {
result.append(carry);
carry = 0;
}
}
if(carry > 0) {
result.append(carry);
}
return result.reverse().toString();
}
}
public class Solution {
static String add(String numStr1, String numStr2) {
if(numStr1.length() < 19 && numStr2.length() < 19) {
return ShortStringSolution.add(numStr1, numStr2);
}
return LongStringSolution.add(numStr1, numStr2);
}
}
For the sake of comprehension of the question
your method's name is addition
you are trying to do a power operation but the result is stored in a variable named multiplication...
there is more than one reason why that code doesnt work...
You need to do something like
Integer.parseInt(string)
in order to parse strings to integers
here the oficial doc

Java IF Statement (Algorithm efficiency improvement)

I used method a that counts the amount of possible choices for getting like number 10 with numbers that are from 0 to 6. Problem is that it just takes too much time when x is like 50 or something. I just need some tips what I should do to make this faster.
Code
public static int count(int x) {
if (x < 0) {
return 0;
}
if (x == 0) {
return 1;
}
int result = 0;
for (int i = 1; i <= 6; i++) {
result += count(x - i);
}
return result;
}
This is a variation on Fibonacci except it is the sum of the last six values instead.
You can use a plain loop which will be faster than memorisation (the first time)
public static long count(int x) {
long a=0, b=0, c=0, d=0, e=0, f=1;
while(x-- > 0) {
long sum = a + b + c + d + e + f;
a = b; b = c; c = d; d = e; e = f;
f = sum;
}
return f;
}
If you call this repeatedly you may as well store all the values in the int range which is likely to be less than 30 the first time and retrieve these values after that.

algorithm for adding the diagonals on a square or rectangular matrix, starting rightwise

I want to add the diagonals in a square or rectangular matrix to emulate the process of adding the partial results in a multiplying algorithm.
Like this:
2412
x 3231
---------
2412
7236
4824
+ 7236
---------
7793172
I need to run this, step by step, to satisfy the requirements of an online judge program. I have already figured out how to get the partial results of the multiplications (the humbers 2412, 7236, 4824, 7236) and I have placed them on a square matrix.
I realized I can get the addition result of this matrix by considering square or rectangular like:
2 4 1 2
7 2 3 6
4 8 2 4
7 2 3 6
and get the result of the addition by adding each diagonal (starting with the upper right one) and taking into account the carry of the addition and using an auxiliary array that has the same number of digits as number_of_digits_in_operand_a + number_of_digits_in_operand_b (operand a being 2412 and operand b being 3231, in this case).
For example, the array result, on its rightmost position should be:
result[(digits_a+digits_b)-1] = partialResult[0][3];
next:
result[digits_a+digits_b]=(partialResult[0][2] + partialResult[1][3] + carry) %10;
newCarry = (partialResult[0][2] + partialResult[1][3] + carry) / 10;
Well, I'm stuck writing the double nested loop that's supposed to add these diagonals starting with the upper right one. Help. Please.
I ended up using this (don't ask why it converts a BigInteger to an ArrayList and viceversa, it's a bizarre homework requirement).
public static BigInteger simpleMultiply(BigInteger x, BigInteger y) throws IOException {
char [] longerNum;
char [] shorterNum;
ArrayList<Integer> multResult= new ArrayList<Integer>(2000);
if(x.compareTo(y)>=0){ // x is a longer/equal num
longerNum = x.toString().toCharArray();
shorterNum = y.toString().toCharArray();
}
else { //y is a longer num
longerNum = y.toString().toCharArray();
shorterNum = x.toString().toCharArray();
}
//shorter num equals the number of rows in partial result
// longer num + 1 equals the number of columns in partial result
int [][] partialResult = new int [shorterNum.length][longerNum.length+1];
int pastCarry=0;
int result=0;
int carry=0;
for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--){
pastCarry=0;
for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
{
int sInt = Integer.parseInt(""+shorterNum[sIndex]+"");
int lInt = Integer.parseInt(""+longerNum[lIndex]+"");
int product = sInt*lInt;
if (lIndex==0){
result = (pastCarry+product)% 10;
carry = (pastCarry+product) / 10;
pastCarry = carry;
partialResult [sIndex][lIndex+1] = result; //one more column element in partialResult
partialResult[sIndex][lIndex] = carry;
}
else {
result = (pastCarry+product) % 10;
carry = (pastCarry+product) / 10;
pastCarry = carry;
partialResult [sIndex][lIndex+1] = result;//one more column element in partialResult
}
}
}
for (int i=0; i<partialResult.length;i++)
for (int j=0; j<partialResult[0].length;j++)
{
System.out.print(partialResult[i][j] + " ");
if (j==partialResult[0].length-1){System.out.println();}
}
int auxColumn=0;
int diagonalAcum=0;
//add diagonals
int copyDigit=0;
int carryDigit=0;
int lastCarry=0;
rowCycle:
for (int column=partialResult[0].length-1; column>=0; column--){
diagonalAcum=0; //carryDigit=0;
diagonalAcum+=carryDigit;
auxColumn=column;
for (int row=0; row<partialResult.length; row++){
if (auxColumn+1 ==partialResult[0].length){
diagonalAcum+=partialResult[row][auxColumn++];
copyDigit=diagonalAcum % 10;
carryDigit=diagonalAcum / 10;
multResult.add(copyDigit);
continue rowCycle;
}
diagonalAcum+=partialResult[row][auxColumn++];
} //end row cycle
copyDigit= diagonalAcum % 10;
carryDigit=diagonalAcum / 10;
multResult.add(copyDigit);
if(column==0){
lastCarry = carryDigit;
}
}
carryDigit=0; //reset
int diagonal2Acum=0;
// diagonal2Acum +=lastCarry;
int auxRow;
int diagCarry=0;
int rowLimit=partialResult.length-1;
int colLimit=partialResult[0].length-1;
int initialRow=1;
int colIndex=0;
for (int row=initialRow;row<=rowLimit;row++){
diagonal2Acum=0;
diagonal2Acum +=lastCarry;
lastCarry=0;
auxRow = row;
colIndex=0;
// partialResult[auxRow][]
while ((auxRow<=rowLimit) && (colIndex<=colLimit)){
diagonal2Acum+= partialResult[auxRow++][colIndex++];
}
if ((colIndex==0)&&(row==rowLimit)) {
copyDigit=(diagonal2Acum+carryDigit)%10;
carryDigit=(diagonal2Acum+carryDigit)/10;
multResult.add(copyDigit);
multResult.add(carryDigit);
}
else {
copyDigit=(diagonal2Acum+carryDigit)%10;
carryDigit=(diagonal2Acum+carryDigit)/10;
multResult.add(copyDigit);
}
} // end row for
StringBuilder appended = new StringBuilder();
for (int i=multResult.size()-1;i>=0;i--){
appended.append(multResult.get(i));
}
System.out.println("result is " + appended.toString());
BigInteger the_result1 = new BigInteger(appended.toString());
return the_result1;
}
Assume your partialResult dimensions are width and height you can add by the following two loops (see it here in action):
int digit = width + height - 1;
int carry = 0;
for (int d1 = width - 1; d1 >= 0; d1--) {
for (int r = 0; r < height && d1 + r < width; r++)
carry += partialResult[r][d1 + r];
result[--digit] = carry % 10;
carry /= 10;
}
for (int d2 = 1; d2 < height; d2++) {
for (int c = 0; c < width && d2 + c < height; c++)
carry += partialResult[d2 + c][c];
result[--digit] = carry % 10;
carry /= 10;
}
Note: Carry may be non-empty at the end meaning another digit before the first one in result.

Categories

Resources