This program does the division for very large numbers (i need it just up to 1000 digits). because no data type can handle very large numbers we use arrays.
I'm trying to translate this Java program to C. I have done some of it but having troubles converting strings to a C compatible data type. remember we need to take numbers as string then convert to int.
the biggest challenge seems to be String, StringBuilder and append. i have no idea how to translate these.
having most trouble with:
if (len1 < len2) return new String[]{"0", n1};
StringBuilder digits = new StringBuilder();
String n3 = n1.substring(0, len2);
Java code:
import java.io.*;
import java.util.*;
class BigDiv
{
public static void main(String[] args)
{
String n1 = "30";
String n2 = "2";
String[] results = Divide(n1, n2);
System.out.println("Quotient is : " + results[0]);
System.out.println("Remainder is : " + results[1]);
}
static String[] Divide(String n1, String n2)
{
Boolean negative = false;
if (n1.charAt(0) == '-' ^ n2.charAt(0) == '-') negative = true;
if (n1.charAt(0) == '-') n1 = n1.substring(1);
if (n2.charAt(0) == '-') n2 = n2.substring(1);
if (n1.equals("0") && n2.equals("0"))
{
return new String[] {"Not a number", "0"};
}
if (n2.equals("0"))
{
if (!negative) return new String[] {"Infinity", "0"};
return new String[] {"-Infinity", "0"};
}
int len1 = n1.length();
int len2 = n2.length();
if (len1 < len2) return new String[]{"0", n1};
StringBuilder digits = new StringBuilder();
String n3 = n1.substring(0, len2);
int len3 = len2;
String n4;
int quotient;
int index = len2 - 1;
while(true)
{
quotient = 0;
while(true)
{
n4 = Subtract(n3, n2);
if (n4 == "-1")
{
break;
}
quotient++;
//System.out.println(quotient);
if (n4 == "0")
{
n3 = "0";
break;
}
n3 = n4;
}
if (digits.toString().equals("0"))
{
digits.setCharAt(0, (char)(quotient + 48));
}
else
{
digits.append((char)(quotient + 48));
}
if (index < len1 - 1)
{
index++;
if (n3.equals("0")) n3 = "";
n3 += n1.charAt(index);
len3 = n3.length();
}
else
{
String result = new String(digits);
if (negative)
{
if (!result.equals("0")) result = "-" + result;
if (!n3.equals("0")) n3 = "-" + n3;
}
return new String[]{result, n3};
}
}
}
static String Subtract(String n1, String n2)
{
int len1 = n1.length();
int len2 = n2.length();
if (len1 < len2) return "-1";
int max = Math.max(len1, len2);
int[] ia1 = new int[max];
int[] ia2 = new int[max];
int[] ia3 = new int[max];
for(int i = max - len1; i < max; i++) ia1[i] = n1.charAt(i + len1 - max) - 48;
for(int i = max - len2; i < max; i++) ia2[i] = n2.charAt(i + len2 - max) - 48;
int diff = 0;
int carry = 0;
for(int i = max - 1; i >= 0; i--)
{
diff = ia1[i] - ia2[i] - carry;
carry = 0;
if (diff < 0)
{
diff += 10;
carry = 1;
}
ia3[i] = diff;
}
if (carry == 1) return "-1";
// find first non-zero element of array ia3
int first = -1;
for (int i = 0; i < max; i++)
{
if (ia3[i] != 0)
{
first = i;
break;
}
}
if (first == -1) first = max - 1;
char[] c3 = new char[max - first];
for(int i = first; i < max; i++) c3[i - first] = (char)(ia3[i] + 48);
//System.out.println("c IS : " + c3[0]);
return new String(c3);
}
my C code so far: (in divide function there is a check for NaN and Negative numbers which i don't really need. also i should not use VLA.)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int Divide(char n1[], char n2[]);
int Subtract(char n1[], char n2[]);
int main()
{
char n1[] = "30";
char n2[] = "2";
char results[] = Divide(n1, n2);
printf("Quotient is : %d", results[0]);
printf("Remainder is : %d", results[1]);
}
int Divide(char n1[], char n2[])
{
/*Boolean negative = false;
if (n1[0] == '-' ^ n2[0] == '-') negative = true;
if (n1[0] == '-') n1 = n1.substring(1);
if (n2[0] == '-') n2 = n2.substring(1);
if (n1.equals("0") && n2.equals("0"))
{
return new String[] {"Not a number", "0"};
}
if (n2.equals("0"))
{
if (!negative) return new String[] {"Infinity", "0"};
return new String[] {"-Infinity", "0"};
}*/
int len1 = strlen(n1);
int len2 = strlen(n2);
if (len1 < len2) return new String[]{"0", n1};
StringBuilder digits = new StringBuilder();
String n3 = n1.substring(0, len2);
int len3 = len2;
String n4;
int quotient;
int index = len2 - 1;
while(true)
{
quotient = 0;
while(true)
{
n4 = Subtract(n3, n2);
if (n4 == "-1")
{
break;
}
quotient++;
if (n4 == "0")
{
n3 = "0";
break;
}
n3 = n4;
}
if (digits.toString().equals("0"))
{
digits.setCharAt(0, (char)(quotient + 48));
}
else
{
digits.append((char)(quotient + 48));
}
if (index < len1 - 1)
{
index++;
if (n3.equals("0")) n3 = "";
n3 += n1[index];
len3 = n3.length();
}
else
{
String result = new String(digits);
if (negative)
{
if (!result.equals("0")) result = "-" + result;
if (!n3.equals("0")) n3 = "-" + n3;
}
return new String[]{result, n3};
}
}
}
int Subtract(char n1[], char n2[])
{
int len1 = n1.length();
int len2 = n2.length();
if (len1 < len2) return "-1";
int max;
if(len1>len2) max = len1;
else if(len2>len1) max = len2;
else max = len1;
int ia1[max];
int ia2[max];
int ia3[max];
for(int i = max - len1; i < max; i++) ia1[i] = n1[i + len1 - max] - 48;
for(int i = max - len2; i < max; i++) ia2[i] = n2[i + len2 - max] - 48;
int diff = 0;
int carry = 0;
for(int i = max - 1; i >= 0; i--)
{
diff = ia1[i] - ia2[i] - carry;
carry = 0;
if (diff < 0)
{
diff += 10;
carry = 1;
}
ia3[i] = diff;
}
if (carry == 1) return "-1";
// find first non-zero element of array ia3
int first = -1;
for (int i = 0; i < max; i++)
{
if (ia3[i] != 0)
{
first = i;
break;
}
}
if (first == -1) first = max - 1;
char c3[max - first];
for(int i = first; i < max; i++) c3[i - first] = (char)(ia3[i] + 48);
return new String(c3);
}
Strings in C are simply sequences of characters terminated by a 0-valued byte. There is no dedicated string type; they are stored as arrays of char, and operators such as =, +, and == are not defined for arrays.
To assign strings, use the strcpy library function. To append strings to each other, you use the strcat library function. To compare strings, use strcmp.
You must do your own memory management; C will not automatically allocate more memory as you extend a string, nor will it do any automatic garbage collection when there are no more references to that memory, meaning you must explicitly deallocate any dynamically allocated memory. Use malloc or calloc to allocate memory, realloc to allocate or extend a buffer that's been allocated with malloc, calloc, or realloc, and free to deallocate memory that was allocated with malloc, calloc, or realloc.
malloc does not initialize the dynamically-allocated memory; calloc will initialize it to all-bits-0.
Here's some sample C code that will allocate, assign, append, compare, and deallocate a string:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define INITIAL_SIZE 20
int main( void )
{
/**
* Allocate space to store a string; the +1 is to make sure
* we have space for the 0 terminator.
*/
char *str1 = calloc( INITIAL_SIZE+1, sizeof *str1 );
size_t str1size = INITIAL_SIZE + 1;
/**
* str2 will point to a string literal; literals are stored as
* arrays of char such that they are allocated at program startup
* and held until the program terminates. String literals may
* not be modified, so we're declaring the pointer as const char *.
*/
const char *str2 = " of the Emergency Broadcast System";
/**
* Copy a string to that buffer
*/
strcpy( str1, "This is a test" );
/**
* Extend the buffer to hold more stuff; typical strategy is
* to double the buffer size each time. For this particular
* example this loop should only run once.
*/
while ( strlen( str1 ) + strlen( str2 ) > str1size)
{
char *tmp = realloc( str1, 2 * str1size );
if ( !tmp )
{
// realloc failed, for this example we treat it as a fatal error
exit( -1 );
}
str1 = tmp;
str1size *= 2;
}
/**
* Append to the buffer
*/
strcat( str1, str2 );
// do something interesting with str1 here
/**
* Deallocate the buffer
*/
free( str1 );
return 0;
}
You must make sure your target buffer is large enough to hold whatever you're writing to it. C doesn't do bounds checking on array accesses, and it won't throw an exception if you try to read or write outside of the array bounds (unless you're trying to access protected memory, but that's a system exception, not a language exception).
Related
basically i have an integer n = 23456 and i want to swap the second and fourth digit, so i = 2 and j = 4. So the output would be 25436. I canĀ“t use any Java class, so I supose that one of the ways to do it is by divide the number on powers of 10 and keep the rest on a new variable.
this is what i have so far:
public static int powerOfTen(int n) {
int p = 10;
while(n-1 > 0) {
p = p*10;
n--;
}
return p;
}
public static int swapNum(int n, int i, int j) {
int swap = 1;
int count = numDigits(n);
int digit1 = nDigit(n, i);
int digit2 = nDigit(n, j);
if(i > j) {
swap = n/powerOfTen(i);
int rest = n%powerOfTen(i);
rest = rest/10;
swap = swap*powerOfTen(i);
}
}
Here's your code with some modifications:
public class Main
{
// Count the number of digits in an integer
static int numDigits(int n)
{
if (n == 0) return 1;
int count = 0;
while (n != 0) {
count++;
n /= 10;
}
return count;
}
// Reverse an integer
static int reverseNumber(int n)
{
int result = 0;
while (n != 0) {
result = result * 10 + n % 10;
n /= 10;
}
return result;
}
// Get the nth digit - from the left
static int nDigit(int n, int index)
{
n = reverseNumber(n);
for (int i = 0; i < index; i++) {
n /= 10;
}
return n % 10;
}
static int swapNum(int n, int i, int j)
{
// Make indexes 0-based
i = i - 1;
j = j - 1;
int count = numDigits(n);
int digit1 = nDigit(n, i);
int digit2 = nDigit(n, j);
int result = 0;
for (int k = count - 1; k >= 0; --k) {
int digit;
// Get the correct digit, i, j, or current
if (k == i) digit = digit2;
else if (k == j) digit = digit1;
else digit = n % 10;
result = result * 10 + digit;
n /= 10;
}
return reverseNumber(result);
}
public static void main(String[] args) {
System.out.println(swapNum(12345678 , 4, 5));
}
}
You can't use any class? what about convert number to char array, swap and parse it back?
// helper function to convert char array to int
public static int parseInt(char[] chars) {
int result = 0; // accumulator
int idx_value = 1; // power of ten counter
for (int i = chars.length - 1; i >= 0; i--) { // loop from tail to head
// char - '0' mean it will convert '0' to 0 and '1' will be 1 so on.
result += (chars[i] - '0') * idx_value;
idx_value *= 10;
}
return result;
}
public static int swapNum(int n, int i, int j) {
// convert number to char array
char[] chars = ("" + n).toCharArray();
// use zero based index
i-=1;j-=1;
// perform swap
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
// convert char array back to int
return parseInt(chars);
}
I need to add two very large numbers without using BigInteger. I am taking two string parameters but the below code only works with strings of equal length otherwise it throws IndexOutOfBoundsException. How can I fix that by adding big numbers irrespective of their length?
public static String add(String a, String b) {
int carry = 0;
String result = "";
for (int i = a.length() - 1; i >= 0; i--) {
int digitA = a.charAt(i) - 48;
int digitB = b.charAt(i) - 48;
int resultingNumber = digitA + digitB + carry;
if (resultingNumber >= 10) {
result = (resultingNumber % 10) + result;
carry = 1;
} else {
result = resultingNumber + result;
carry = 0;
}
}
if (carry > 0) {
result = carry + result;
}
return result;
}
There is no need to pad any of the parameters with zeroes. Also, for better performance, don't use String + String.
Create a char[] for the result. Since the result can be 1 longer than the longest input, create it at that size.
Then iterate from end of input strings, setting each character in the result.
Then eliminate any leading zeroes, resulting from inputs not overflowing or from inputs having leading zeroes.
Finally, create a String from the char[] using the String(char[] value, int offset, int count) constructor.
Like this:
public static String add(String a, String b) {
int i = a.length();
int j = b.length();
int k = Math.max(i, j) + 1; // room for carryover
char[] c = new char[k];
for (int digit = 0; k > 0; digit /= 10) {
if (i > 0)
digit += a.charAt(--i) - '0';
if (j > 0)
digit += b.charAt(--j) - '0';
c[--k] = (char) ('0' + digit % 10);
}
for (k = 0; k < c.length - 1 && c[k] == '0'; k++) {/*Skip leading zeroes*/}
return new String(c, k, c.length - k);
}
Test
public static void main(String[] args) {
test("1234", "2345"); // test equal-sized inputs, no carry-over
test("12345", "12345"); // test equal-sized inputs, with carry-over
test("54321", "54321"); // test equal-sized inputs, longer result
test("99999", "99999"); // test max result
test("5", "1234"); // test odd-sized inputs, no carry-over
test("5", "12345"); // test odd-sized inputs, with carry-over
test("1", "99999"); // test with a carry-over to longer result
test("001", "00002"); // test leading zeroes in input are eliminated
test("000", "00000"); // test leading zero removal leaves 1 zero
}
public static void test(String a, String b) {
// Test add is commutative, i.e. a+b = b+a
System.out.printf("%s + %s = %s = %s%n", a, b, add(a, b), add(b, a));
}
Output
1234 + 2345 = 3579 = 3579
12345 + 12345 = 24690 = 24690
54321 + 54321 = 108642 = 108642
99999 + 99999 = 199998 = 199998
5 + 1234 = 1239 = 1239
5 + 12345 = 12350 = 12350
1 + 99999 = 100000 = 100000
001 + 00002 = 3 = 3
000 + 00000 = 0 = 0
You can prepend the shorter string with zeros to make it match the length of the other number:
private static String leftPad(String s, int length) {
if (s.length() >= length)
return s;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length - s.length(); i++)
sb.append("0");
return sb.toString() + s;
}
public static String add(String originalA, String originalB) {
int maxLength = Math.max(originalA.length(), originalB.length());
String a = leftPad(originalA, maxLength);
String b = leftPad(originalB, maxLength);
... rest of your method
You can left pad with zeroes the strings like this:
int longestString = Math.max(a.length(), b.length());
a = String.format("%1$" + longestString + "s", a).replace(' ', '0');
b = String.format("%1$" + longestString + "s", b).replace(' ', '0');
This will add leadings spaces to fill the "gap" and then replace them with zeroes.
Class:
public class Mission09 {
public static void main(String[] args) {
System.out.println(add("1", "1333"));
}
public static String add(String a, String b) {
int carry = 0;
String result = "";
int longestString = Math.max(a.length(), b.length());
a = String.format("%1$" + longestString + "s", a).replace(' ', '0');
b = String.format("%1$" + longestString + "s", b).replace(' ', '0');
for (int i = a.length() - 1; i >= 0; i--) {
int digitA = a.charAt(i) - 48;
int digitB = b.charAt(i) - 48;
int resultingNumber = digitA + digitB + carry;
if (resultingNumber >= 10) {
result = (resultingNumber % 10) + result;
carry = 1;
} else {
result = resultingNumber + result;
carry = 0;
}
}
if (carry > 0) {
result = carry + result;
}
return result;
}
}
I/O:
System.out.println(add("1", "1333"));
1334
System.out.println(add("12222", "1333"));
13555
Given two numbers as input, return the sum of the numbers. Note that the numbers can be very large and hence are provided as Strings
Sample Input #1:
add("2354725234782357","9999999999999999999999999988888888888")
Sample Output #1:
10000000000000000000002354714123671245
Implementation:
public String add(String str1, String str2) {
int max = str1.length() > str2.length() ? str1.length() : str2.length();
int n1[] = new int[max];
int n2[] = new int[max];
for (int i = 0; i < str1.length(); i++) {
n1[i] = str1.charAt(str1.length() - 1 - i);
}
for (int i = 0; i < str2.length(); i++) {
n2[i] = str2.charAt(str2.length() - 1 - i);
}
int carry = 0;
int sum[] = new int[max + 1];
int k = 0;
for (k = 0; k < max; k++) {
sum[k] = (n1[k] + n2[k] + carry) % 10;
if ((n1[k] + n2[k] + carry) >= 10) {
carry = 1;
} else {
carry = 0;
}
}
sum[max] = carry;
String result = "";
return result;
}
I have implemented my logic but I don't know how to get the output as a string.
Why don't use BigInteger this is much easier and still native java.
private static String add(String s1, String s2)
{
BigInteger n1 = new BigInteger(s1);
BigInteger n2 = new BigInteger(s2);
return n1.add(n2).toString();
}
Anyway, there is one bug in your Code. Dont cast char to int the ascii value is used, which is wrong. Parse it with Character.getNumericValue();
If you have done this, you can concat sum array to a string in reversed order.
Solution:
public static String add(String str1, String str2) {
int max = str1.length() > str2.length() ? str1.length() : str2.length();
int n1[] = new int[max];
int n2[] = new int[max];
for (int i = 0; i < str1.length(); i++)
{
// conver char to int
n1[i] = Character.getNumericValue(str1.charAt(str1.length() - 1 - i));
}
for (int i = 0; i < str2.length(); i++) {
// conver char to int
n2[i] = Character.getNumericValue(str2.charAt(str2.length() - 1 - i));
}
int carry = 0;
int sum[] = new int[max + 1];
int k = 0;
for (k = 0; k < max; k++) {
sum[k] = (n1[k] + n2[k] + carry) % 10;
if ((n1[k] + n2[k] + carry) >= 10) {
carry = 1;
} else {
carry = 0;
}
}
sum[max] = carry;
// concat array in reverse order
StringBuilder sb = new StringBuilder();
for(int i = sum.length - 1; i >= 0; i--)
sb.append(sum[i]);
return sb.toString();
}
Input
add("2354725234782357","9999999999999999999999999988888888888")
Output
10000000000000000000002354714123671245
There is a logic error in your code: you are adding the char value of each integer instead of the integer themselves. You can get the numeric value of a char using Character.getNumericValue(char ch).
Then, you can construct the resulting String by looping over the sum array. The loop must be done in reverse order (to get the correct order). Beware of the first value sum[max], if it is 0, we must not add it to the String (otherwise, we will get a value padded with a 0):
public static String add(String str1, String str2) {
int max = Math.max(str1.length(), str2.length());
int n1[] = new int[max];
int n2[] = new int[max];
for (int i = 0; i < str1.length(); i++) {
//n1[i] = str1.charAt(str1.length() - 1 - i);
n1[i] = Character.getNumericValue(str1.charAt(str1.length() - 1 - i));
}
for (int i = 0; i < str2.length(); i++) {
//n2[i] = str2.charAt(str2.length() - 1 - i);
n2[i] = Character.getNumericValue(str2.charAt(str2.length() - 1 - i));
}
int carry = 0;
int sum[] = new int[max + 1];
int k = 0;
for (k = 0; k < max; k++) {
sum[k] = (n1[k] + n2[k] + carry) % 10;
if ((n1[k] + n2[k] + carry) >= 10) {
carry = 1;
} else {
carry = 0;
}
}
sum[max] = carry;
StringBuilder sb = new StringBuilder();
if (sum[max] > 0) {
sb.append(String.valueOf(sum[max]));
}
for (int i = max - 1; i >= 0; i--) {
sb.append(String.valueOf(sum[i]));
}
return sb.toString();
}
Note that you can also replace
int max = str1.length() > str2.length() ? str1.length() : str2.length();
with
int max = Math.max(str1.length(), str2.length());
I have modified some code:(you can avoid array creation)
public static String add(String str1, String str2) {
int carry=0;
StringBuilder sum=new StringBuilder();
int l1=str1.length();
int l2=str2.length();
while(l1>0 && l2>0){
int s=Character.getNumericValue(str1.charAt(--l1))+Character.getNumericValue(str2.charAt(--l2))+carry;
if(s<10){
sum.append(s);
}else{
sum.append(s%10);
carry=s/10;
}
}
if(l2>0){
while(l2>0){
int s=Character.getNumericValue(str2.charAt(--l2))+carry;
if(s<10){
sum.append(s);
}else{
sum.append(s%10);
carry=s/10;
}
}
}
if(l1>0){
while(l2>0){
int s=Character.getNumericValue(str1.charAt(--l1))+carry;
if(s<10){
sum.append(s);
}else{
sum.append(s%10);
carry=s/10;
}
}
}
if(carry>0){
sum.append(carry);
}
return sum.reverse().toString();
}
You can use a StringBuilder to append all the digits from your int[] from max to 0.
StringBuilder sb = new StringBuilder();
for (int i=max; i>=0; i--)
{
sb.append(String.valueOf(sum[i]));
}
String result = sb.toString();
You can also improve this to skip leading zeroes if you want:
boolean leadingZero = true;
StringBuilder sb = new StringBuilder();
for (int i=max; i>=0; i--)
{
if (sum[i] != 0)
{
leadingZero=false;
}
if (!leadingZero)
{
sb.append(String.valueOf(sum[i]));
}
}
String result = sb.toString();
I need some help on a program i'm supposed to create. i'm supposed to create a program that reads two strings of any length that are user inputted and it subtracts or adds them together. i'm NOT allowed to convert these strings into numbers before the operation. this is what I got so far.My teacher mentioned something like converting the strings into uni-code to add and subtract them but i have no idea how to do it as we haven't even learned uni-code. HERE IS MY CODE:
import java.util.Scanner;
public class Number {
private char Sign;
private String Whole;
private String Fraction;
public static void main(String[] args) {
Scanner Keyboard = new Scanner (System.in);
System.out.println("This program adds or subtracts numbers of any lengths, please add two numbers: ");
String num1 = Keyboard.nextLine();
System.out.println("Enter the second number: ");
String num2 = Keyboard.nextLine();
String sum = " ";
int length = num1.length();
int carry = 0;
public Number Add(Number RHS) {
for (int i = length -1 ; i >= 0; i--) {
char c1 = num1.charAt(i);
char c2 = num2.charAt(i);
int tempSum = (c1 - 48) + (c2 - 48) + carry;
carry = tempSum / 10;
int sumDigit = tempSum % 10;
sum = (char) (sumDigit + 48) + sum;
if (carry == 1) {
sum = "1" + sum;
}
}
}
}
public Number (double n) {
Whole = " ";
Fraction = " ";
if (n >= 0) {
Sign = '+';
}
else
{
Sign = '-';
n = Math.abs(n);
String numString = new Double(n).toString();
int position = numString.indexOf(".");
}
}
}
public static String add(String as, String bs){
ArrayList<String> BigNum = new ArrayList<>();
int m = as.length()-1;
int n = bs.length()-1;
int min = m > n ? n : m ;
int max = 0;
String s;
if(n > m){
s = bs;
max = n;
}else{s = as ; max = m;}
Integer carry = 0;
while(true){
int a = Integer.parseInt(Character.toString(as.charAt(m)));
int b = Integer.parseInt(Character.toString(bs.charAt(n)));
Integer c = a + b + carry;
if(c > 9){
carry = 1;
c %=10;
}else carry = 0;
BigNum.add(c.toString());
n--; m--; min--; max--;
if ( min < 0 ) {
if(carry !=0 && max < 0 )
BigNum.add(carry.toString());
break;
}
}
Integer c = carry;
while(max >= 0) {
c += Integer.parseInt(Character.toString(s.charAt(max)));
BigNum.add(c.toString());
c = 0;
max--;
}
String s2 = "";
for (int i = BigNum.size()-1; i >= 0; i--) {
s2 +=BigNum.get(i);
}
return s2;
}
I need to add 8 numbers together from a string.E.g. If someone enters say 1234 it will add the numbers together 1 + 2 + 3 + 4 = 10 then 1 + 1 = 2. I have done this so far. I cannot figure out how to add these numbers up using a for loop.
String num2;
String num3;
num2 = (jTextField1.getText());
num3 = num2.replaceAll("[/:.,-0]", "");
String[] result = num3.split("");
int inte = Integer.parseInt(num3);
for (int i = 0; i < 8; i++){
// Stuck
}
How about that (I skipped exceptions...):
String[] sNums = jTextField1.getText().replaceAll("[^1-9]", "").split("(?<!^)");
int sum = 0;
for (String s : sNums) {
sum += Integer.parseInt(s); // add all digits
}
while (sum > 9) { // add all digits of the number, until left with one-digit number
int temp = 0;
while (sum > 0) {
temp += sum % 10;
sum = sum / 10;
}
sum = temp;
}
For every element in result, you need to convert it to an int, then add it to some variable, maybe called sum.
int sum = 0;
// for every String in the result array
for (int i = 0; i < BOUND; i++) {
// convert s[i] to int value
// add the int value to sum
}
This pseudo code should do it without splitting, arrays etc.
String s = "1234.56";
int sum = 0;
int i = 0;
while (i < s.length()) {
char c = s.charAt(i)
if (c >= '0' && c <= '9') sum += c - '0';
i++;
}
Should result in sum = 21
public static int addAll(String str) {
str = str.replaceAll("[^1-9]", "");
if (str.length() == 0)
return 0;
char[] c = str.toCharArray();
Integer result = c[0] - 48;
while (c.length > 1) {
result = 0;
for (int i = 0; i < c.length; i++) {
result += c[i] - 48;
}
c = result.toString().toCharArray();
}
return result;
}