Java, converting string to integers then add all the integers together - java

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;
}

Related

How can I swap 2 digits (i,j) from a n number?

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);
}

Draw pattern in Java using numbers and (*)

I'm trying to write a program using Java, that (outputs) the following pattern depending on an input (integer) (n = 5):
0********1
23******45
678****901
2345678901
As you noticed:
input(3) represent 3 rows
single row digits (n * 2)
Digits should start from 0 to 9 and then repeat until the pattern is fully done
First row should have only 2 numbers (start 0 end 1)
(*) will be in between
Next row should have 4 numbers (start 23 end 45) and so on
How can this program written?
Here is my code:
import java.util.Scanner;
public class b_test_2 {
public static void main (String arug[]) {
String star = "*";
int star_count, digit = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please type a number (int)");
int n = sc.nextInt();
while (n != 0){
star_count = n * 2 - 2;
for (int i=0; i<n; i++) {
System.out.print(star);
i = i + 1;
}
String stars = star;
n = n - 1;
for (int i2=0; i2<n; i2++) {
System.out.print(star);
i2 = i2 + 1;
int x = 0;
x = digit;
x = x + 1;
if (x == 10){
x = 0;
System.out.print(digit + stars + digit);
}
}
}
}
}
There are any parts missing in your code, but you also seem to make it more complicated than it is.
To illustrate, and hopefully help you to go in the right direction, here is compact code to do it. Do not hand in this code unless you fully understand how it works.
static void printPattern(int n) {
for (int row = 1, digit = 0; row <= n; row++) {
for (int i = 0; i < row; i++, digit = (digit + 1) % 10)
System.out.print(digit);
for (int i = (n - row) * 2; i > 0; i--)
System.out.print('*');
for (int i = 0; i < row; i++, digit = (digit + 1) % 10)
System.out.print(digit);
System.out.println();
}
}
Test
printPattern(4);
Output
0******1
23****45
678**901
23456789
I case you haven't learned it yet, the % operator calculates the remainder after division.

Java - Summing big Integer with a traditional way

I have nested for loop :
String s1 = "4412";
String s2 = "0123";
int k = 0, l = 0, i3 = 0;
for (int i = s1.length() - 1; i < s1.length(); i--) {
for (int j = s2.length() - 1; j <= i; j--) {
k = Integer.parseInt(Character.toString(s1.charAt(i)));
l = Integer.parseInt(Character.toString(s2.charAt(j)));
i3 = k + l;
System.out.println(i3);
}
}
when I am executing this program I am getting 234 as output. because its taking last element value in the s1 and s2 . S2 keep on repeating loop like this:
1
321
2
321
.
.
so 2+3 ,2+2,2+1 like this its working . But what I am expecting is
4412+123 = 4535
can anyone help me out. Thanks in advance
You coud use split with reverse String and loop throw your arrays like this :
String s1 = "4421";
String s2 = "321";
//reverse and split your string
String[] spl1 = new StringBuilder(s1).reverse().toString().split("");//[1,2,4,4]
String[] spl2 = new StringBuilder(s2).reverse().toString().split("");//[1,2,4,4]
String result = "";
int max = spl1.length > spl2.length ? spl1.length : spl2.length;
for (int i = 0; i < max; i++) {
int k = spl1.length <= i ? 0 : Integer.parseInt(spl1[i]);
int l = spl2.length <= i ? 0 : Integer.parseInt(spl2[i]);
result += (k + l) + "";
}
System.out.println(result);//result 2474
The Idea is :
reverser your Strings 12345 -> 54321
split your Strings [5,4,3,2,1]
find the max between your arrays
loop throw your array and make the addition, if the input not exist use 0, spl1.length <= i ? 0 : Integer.parseInt(spl1[i]);
add the addition to your result.
Edit
Lets back to school :
you can use this instead, the idea is simple :
String s1 = "5768956788678907689076890076544765433564376543564";
String s2 = "657687986578905438732902587349320254893";
String[] spl1 = new StringBuilder(s1).reverse().toString().split("");
String[] spl2 = new StringBuilder(s2).reverse().toString().split("");
String result = "";
int max = spl1.length > spl2.length ? spl1.length : spl2.length;
int rest = 0;
int sum;
for (int i = 0; i < max; i++) {
int k = spl1.length <= i ? 0 : Integer.parseInt(spl1[i]);
int l = spl2.length <= i ? 0 : Integer.parseInt(spl2[i]);
sum = k + l + rest;
if (sum > 9) {
rest = 1;
sum = sum - 10;
} else {
rest = 0;
}
result = (i + 1 == max ? sum + rest * 10 : sum) + result;
}
System.out.println(result);
try these code
String s1 = "4412";
String s2 = "0123";
int k = 0, l = 0;
int num1 = 0, num2 = 0, length = 0;
length = s1.length() > s2.length() ? s1.length() : s2.length();
for (int i = 0; i < length; i++) {
if (i < s1.length()) {
k = Integer.parseInt(Character.toString(s1.charAt(i)));
num1 = num1 * 10 + k;
}
if (i < s2.length()) {
l = Integer.parseInt(Character.toString(s2.charAt(i)));
num2 = num2 * 10 + l;
}
}
int result = num1 + num2;
System.out.println(num1 + "+" + num2 + "=" + result);

adding and subtracting strings in Java

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;
}

string multiplication

I am trying to multiply two strings, but I am getting the wrong answer. Any help will be appreciated:
public class stringmultiplication {
public static void main(String[] args) {
String s1 = "10";
String s2 = "20";
int num = 0;
for(int i = (s1.toCharArray().length); i > 0; i--)
for(int j = (s2.toCharArray().length); j > 0; j--)
num = (num * 10) + ((s1.toCharArray()[i - 1] - '0') * (s2.toCharArray()[j - 1] - '0'));
System.out.println(num);
}
}
public static void main(String[] args) {
String number1 = "108";
String number2 = "84";
char[] n1 = number1.toCharArray();
char[] n2 = number2.toCharArray();
int result = 0;
for (int i = 0; i < n1.length; i++) {
for (int j = 0; j < n2.length; j++) {
result += (n1[i] - '0') * (n2[j] - '0')
* (int) Math.pow(10, n1.length + n2.length - (i + j + 2));
}
}
System.out.println(result);
}
This one should be correct implementation without using integers.
You're multiplying the numbers digit-wise, and you're not handling the powers of 10 correctly.
You need to first parse the strings into integers. You're on the right track here. You can simplify the loop indices, and you only have to call toCharArray once. E.g.:
After parsing, you can multiply the integers.
EDIT: If that's not allowed, you need to implement an algorithm like this one, which is a bit more complicated.
One approach is to make an (n + 1) x (m + n) array (strictly an array of arrays), where m and n are the number of digits in each. It will be initialized to 0, and you can use this as an area to put the rows of the immediate and final results. These are then summed with carry. This is obviously a näive algorithm.
E.g. for the example above:
int[][] intermediates = new int[3][4];
This is an upper bound.
Following is the solution which i suggest, what you forgot doing there is keeping the intermediate value.
public class T{
public static void main(String[] args) {
char[] num1 = "127".toCharArray();
char[] num2 = "32".toCharArray();
int[] intermediate = new int[num1.length];
for (int i = 0 ; i < num1.length ; i++ ) {
for(int j = 0 ; j < num2.length ; j++ ) {
int d1 = num1[num1.length - i - 1]-'0';
int d2 = num2[num2.length - j - 1]-'0';
intermediate[i] += d1 * d2 * (int) Math.pow(10,j);
System.out.printf(" %d X %d = %d\n", d1, d2, intermediate[i]);
}
intermediate[i] *= (int) Math.pow(10,i);
System.out.println(" intermediate : " + intermediate[i]);
}
int sum = 0;
for(int i : intermediate) {
sum += i;
}
System.out.println("Sum is = " + sum);
}
}
I found Peter's Algorithm using the pow function to be a bit confusing.
Here is essentially the same algorithm.
Convert your Strings to char[]'s and then run this.
public static int multiply (char A[], char B[]){
int totalSum = 0, sum = 0;
for (int i = 0; i < A.length; i++){
sum = 0;
for (int j = 0; j < B.length; j++){
sum *= 10;
sum += (A[i] - '0') * (B[j] - '0');
}
totalSum *=10;
totalSum += sum;
}
return totalSum;
}

Categories

Resources