How to find sum of first three digits - java

I'm new in Java and I try to find the sum of first three digits in int number.
I have a number 123456 I want to find the sum of first three digits 123 and then find sum of last three digits 456 and then compare it. I can't understand how to do this. I code next:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int number = scanner.nextInt();
int length = (int) Math.ceil(Math.log10(number));
for (int i = 1; i <= 3; i++) {
System.out.println(i);
}
System.out.println(length);
System.out.println(number);
}
I think that I shoud to use for loop, but I'm not sure. I know how to count the length of a number. But how to how to find the sum of the first three numbers and last three?

Assuming your length is constant (6):
String first = (""+number).substring(0, 3);
String second = (""+number).substring(3, 6);
int firstSum = 0;
int secondSum = 0;
for (int x = 0; x < first.length; x++)
firstSum += Integer.parseInt(first.charAt(x)+"");
for (int x = 0; x < second.length; x++)
secondSum += Integer.parseInt(second.charAt(x)+"");
System.out.println("Sum of first 3: " + firstSum);
System.out.println("Sum of second 3: " + secondSum);
Read the String API- it has a lot of useful methods. For small programs like this, it's usually pretty easy to convert to String, use String methods, then parse back to int.
EDIT: Andy Turner and Jeremy Kato informed me about Character.getNumericValue(). Thus, the statement:
firstSum += Integer.parseInt(first.charAt(x)+"");
Could be changed to:
firstSum += Character.getNumericValue(first.charAt(x));
Likewise for secondSum.

First, probably should correct your spelling of length - though maybe not, because you don't really need that variable to do this.
What your code should do to make this easier for you is to not convert the input into an int immediately. You'll first want to split the input string into two pieces, then take the two numbers and sum them up with a loop.
Here's my idea of what I'd do:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
String input = scanner.nextLine();
String firstHalf = input.substring(0, 3); // note that depending on how
// many digits you want to change, these numbers must change as well.
String secondHalf = input.substring(3);
int sum1 = 0;
int sum2 = 0;
// don't forget: start at 0, not 1!
for(int i = 0; i<=3; i++){
sum1 += Character.getNumericValue(firstHalf.charAt(i));
sum2 += Character.getNumericValue(secondHalf.charAt(i));
// this call to the Character class converts a character to an int.
}
System.out.println(sum1);
System.out.println(sum2);
}
Just note that this code is made to work with your input being 6 characters, and it assumes they're going to be numbers. It'll crash if you enter too few characters in or if you put letters in, but you can always worry about that later.

Here's a straightforward way of doing it, making the assumption that your integer has an even number of digits...
public class Test {
public static void main(String[] args) {
// Makes the assumption that the input integer contains an even number of digits.
int x = 123456;
String s = Integer.toString(x);
int[] count = new int[2];
for (int i = 0; i < s.length(); i++) {
int digit = Integer.parseInt(s.substring(i, i + 1));
int countIndex = (int)Math.floor(i * 2 / s.length());
count[countIndex] += digit;
}
int half = s.length() / 2;
System.out.println("First Sum of " + s.substring(0, half) + ": " + count[0]);
System.out.println("Second Sum of " + s.substring(half) + ": " + count[1]);
}
}
Alternate Method
Here's another way of doing it without using the arrays above, and actually simplified the logic by abstracting the sum to a method.
public class Test {
public static void main(String[] args) {
// Makes the assumption that the input integer contains an even number of digits.
int x = 123456;
String s = Integer.toString(x);
int half = s.length() / 2;
String firstHalf = s.substring(0, half);
String secondHalf = s.substring(half);
System.out.println(firstHalf);
System.out.println(secondHalf);
int sum1 = sumString(firstHalf);
int sum2 = sumString(secondHalf);
System.out.println("Sum 1: " + sum1);
System.out.println("Sum 2: " + sum2);
}
private static int sumString(String s) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
sum += Integer.parseInt(s.substring(i, i + 1));
}
return sum;
}
}

Here is an alternative solution which doesn't use Strings or arrays:
public static void main(String args[]){
int num=123456;
int second = 0;
int first = 0;
second = addLastThree(num);
num /= 1000;
first = addLastThree(num);
System.out.println("first -- > " + first);
System.out.println("second -- > " + second);
}
static int addLastThree(int num){
int sum = 0;
for (int i =0; i<3; i++){
sum += (num/Math.pow(10,i)) % 10;
}
return sum;
}

you can try this code and every line was explained in comments.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int number = scanner.nextInt();
int n=number; //duplicating the value for the reference.
int l = (int) Math.log10(number) + 1; //Length of the number
int half = l/2; //to find half length of the number to sum first and last digits seperately.
int last_Sum = 0; //to store sum of last digits
int first_Sum = 0; //to store sum of first digits
for(int i=0; i<half && number>0; i++){ //to sum last digits
last_Sum = last_Sum + number%10;
number = number/10;
}for(int i=0; i<half && number>0; i++){ //to sum first digits
first_Sum = first_Sum + number%10;
number = number/10;
}
System.out.println("Length of the number "+l);
System.out.println("Number is "+n);
System.out.println("Sum of last digits "+last_Sum);
System.out.println("Sum of first digits "+first_Sum);}}

Related

create a program that prompts the user to enter a number between 1 and 15 and print the sum as shown: 1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10

I seriously need help please
1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10
I don't know how to code the equation part
import java.util.Scanner;
public class Equations {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println ("Enter a number between 1 to 15: ");
int num = scan.nextInt();
int total = 0;
int save;
for(int i=1;i<=num;i++)
{
for(int j=1;j<=num;j++)
{
save = total+i;
i++;
}
System.out.print (save+"="+total);
System.out.println ();
}
}
This is all I have, and it doesn't work.
There are quite a few things off. You're not resetting total or save after each equation. save is an int, so it can't hold the equation string. j needs to increment to i, not num. total is never incremented. i++ doesn't belong in the inner loop.
Here's a simple, correct version:
for (int i = 1; i <= num; i++) {
int sum = 0;
String equation = "";
for (int j = 1; j <= i; j++) {
sum += j;
equation += "+" + j;
}
System.out.println(equation.substring(1) + "=" + sum);
}

Maximum Integer Value java

I was trying to solve the Maximum Integer Value problem form Geeksforgeeks.
The problem states the following:
Given a string S of digits(0-9), your task is to find the maximum value that can be obtained from the string by putting either '*' or '+' operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.
Input:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of input denoting the string.
Output:
For each testcase, print the maximum value obtained.
this is what I did:
class GFG
{
public static void sort(int[] numbers)
{
int n = numbers.length;
for (int i = 1; i < n; ++i)
{
int key = numbers[i];
int j = i - 1;
while (j >= 0 && numbers[j] > key)
{
numbers[j + 1] = numbers[j];
j = j -1 ;
}
numbers[j + 1] = key;
}
System.out.println(numbers.length - 1);
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
int [] maxNum;
for(int i = 0; i< testCases; i++)
{
String numbers = sc.nextLine();
char[] cNumbers = numbers.toCharArray();
maxNum = new int [cNumbers.length];
for(int j = 0; j + 1 < cNumbers.length; j++)
{
int sum = 0;
int mult = 0;
sum = cNumbers[j] + cNumbers[j + 1];
mult = cNumbers[j] * cNumbers[j + 1];
int maxNumber = Math.max(sum, mult);
maxNum[i] = maxNumber;
}
sort(maxNum);
}
}
}
an example of Input:
2
01230
891
My Output:
-1
4
Correct Output:
9
73
What is wrong with my code?!
Just quick glance it would seem if your digit is less than two it should be added. 2 or larger should get multiplied. Not at a PC to test though.
The idea is to put the operators alternatively and choose the maximum results.
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = Integer.parseInt(sc.nextLine());
for (int i = 0; i < testCases; i++) {
String numbers = sc.nextLine();
int max = 0;
for (int j = 0; j + 1 < numbers.length(); j++) {
int next = Integer.parseInt(numbers.substring(j, j+1));
if (max + next > max * next)
max = max + next;
else
max = max * next;
}
System.out.println(max);
}
sc.close();
}
}
After the execution of
int testCases = sc.nextInt();
the buffer contains a new line character. So when executing the line
String numbers = sc.nextLine();
it read '\n' into numbers, so you got -1 as the first output.
Also you need to convert character to Integer before using it any arithmetic operations.
sum = cNumbers[j] + cNumbers[j+1];
mult = cNumbers[j] * cNumbers[j+1];
So the above code will give you wrong results.
I tried the following sample and worked.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputAsString = sc.nextLine();
int testCases = Integer.parseInt(inputAsString);
int maxNumber = 0;
for (int i = 0; i < testCases; i++) {
String numbers = sc.nextLine();
if(!numbers.matches("\\d+")){
System.out.println("Only numeric values are expected.");
continue;
}
char[] cNumbers = numbers.toCharArray();
int sum = 0;
int mult = 1;
for (int j = 0; j < cNumbers.length; j++) {
int nextNumber = Character.getNumericValue(cNumbers[j]);
sum = sum + nextNumber;
mult = mult * nextNumber;
maxNumber = mult > sum ? mult : sum;
sum = maxNumber;
mult = maxNumber;
}
System.out.println(maxNumber);
}
sc.close();
}
I read your description and what you do is wrong. please read question carefully specially the example in reference site.
as mentioned in comments by moilejter you use sc.nextInt() which doesn't read '\n' and make problem. the next sc.nextLine() will read only a empty string and your program throw exception.
Second problem is that you must calculate max continuously and you don't need an int array (you calculate max result of operation between two successive number and save them in an array which is not correspond to max integer value. you only find max between each two digit but not max of operation on all digit).
Third problem is that you use character as numbers which is made incorrect result. (you must convert them to integer)
So there is a code that works for your output:
public class GFG
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = Integer.valueOf(sc.nextLine());
for (int i = 0; i < testCases; i++)
{
String numbers = sc.nextLine();
char[] cNumbers = numbers.toCharArray();
long maxUntilNow = cNumbers[0] - '0';
for (int j = 1; j < cNumbers.length; j++)
{
int numberOfThisPlace = cNumbers[j] - '0';
maxUntilNow = Math.max(maxUntilNow + numberOfThisPlace,
maxUntilNow * numberOfThisPlace);
}
System.out.println(maxUntilNow);
}
}
}
I hope this is what you want.
As per the problem statement, we need to obtain maximum value from the string by putting either * or + operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.
So, this can be solved in O(n) without using any sorting algorithm.
The simple logic behind the solution is whenever you find "0" or "1" in any of the operands use "+" and the rest of the places use "*".
Here is my solution which got successfully submitted:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int T = Integer.parseInt(scan.nextLine());
while(T-- > 0) {
String str = scan.nextLine();
maxValue(str);
}
}
static void maxValue(String str) {
long maxNumber = 0;
for(int i = 0; i < str.length(); i++) {
int n = Character.getNumericValue(str.charAt(i));
if (maxNumber == 0 || maxNumber == 1 ||
n == 0 || n == 1) {
maxNumber += n;
} else {
maxNumber *= n;
}
}
System.out.println(maxNumber);
}
}

Reverse numerical numbers without use of libraries

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++)
{
int number = input.nextInt();
int reverse = 0;
while (number != 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
System.out.println(reverse);
}
}
}
All numbers reverse well but I have problem with reversing numbers that end with zero e.g numbers like 10000 instead of reversing result being 00001 it gives the result as 1 which is not what the question wants is there a way to use integers or string will be the best and easier approach? Thank you
Try the reversing of string concept
String s ="10000";
String n= "";
for(int i=0; i<s.length(); i++){
n = s.charAt(i) + n;
}
System.out.println(n);
You can create a variable length, and use System.out.printf to format output.
With %0 + length + d, it will add 0 on the left to make the output have this length.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++)
{
int number = input.nextInt();
int reverse = 0;
int length = String.valueOf(number).length();
while (number != 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
System.out.printf("%0" + length + "d", reverse);
}
}
}
You could also solve it with a StringBuilder. It already has a method called reverse:
public String reverseInput(int number) {
String s = Integer.toString(number);
return new StringBuilder(s).reverse().toString();
}
You can't have a Integer beginning with 0 except 0 itself. So you will have to work with Strings or other datastructures.

Formatting Pascal's Triangle in Java

I've recently been teaching myself Java and I made a piece of code to produce Pascal's triangle. However, I can't get it to print out properly in a triangle. I can't figure out how to take into account numbers with multiple digits. Here's what I have so far:
public class Pas{
public static void main(String[] args){
pas(20);
}
public static void pas(int rows){
for(int i = 0; i < rows; i++){
String spaces = "";
int counter = (rows + 30)/2 - i;
for(int f = counter; f > 0; f --){
spaces += " ";
}
System.out.print(spaces);
for(int j = 0; j <= i; j++){
System.out.print( ncr(i, j) + " ");
}
System.out.println();
}
}
public static long ncr(int n, int r){
return fact(n) / (fact(r) * fact(n - r));
}
public static long fact(int n){
long ans = 1;
for(int i = 2; i <= n; i++){
ans *= i;
}
return ans;
}
Please keep in mind I'm a complete beginner and have never had any actual instruction. Everything I know is from the internet and messing around in Eclipse.
So the problem you're having is with spacing.
You are using always one space after a number, which is a problem because one number can be of length 1 - i.e: 1,2,3,4,5,6,7,8,9 - and another can be of length 5 - i.e. 31824. Because of that your triangle is wider on the right side.
To change that you have to reserve equal space for all your numbers - so if your biggest number is 184756 then for every number you print you have to reserve place for 6 digits and 1 empty space after them.
Also your initial spacing is not related to the number of rows, which in general can generate problems (if you would like to make triangle bigger than 30 - your current constant).
So there are two places where I would suggest changes:
First is this (1):
int counter = (rows + 30)/2 - i;
Here 30 is a constant that works for your 20 dimention triangle, but it's not elegant and won't work for bigger triangles. So I would suggest something like this (2):
int counter = (maxNumberLength*(numberOfRows - i))/2;
maxNumberLength is the maximum length the numbers in your triangle can get. How to calculate it? I'have estimated like that (3):
Math.pow(2d, numberOfRows.doubleValue());
This power will always be bigger than the biggest value in the triangle, but not by much. You can do it differently - it's first that came to my mind.
So back to (2)... the numberOfRows is the number of rows in the triangle. You substract i before multiplying to get the initial space maximumNumberLength/2 smaller in every row (so that it has a left slope).
The second thing that I would suggest changing is this:
System.out.print( ncr(i, j) + " ");
That's the most important part as you always add 1 space. If maximum number length is 6, then you should add 6 spaces after 1, 5 spaces after 20 and so on. Thats why I suggest creating a method that would return you the number of spaces you need (4):
private String spaces(final Long number, final int maxNumberLength)
{
StringBuilder spaces = new StringBuilder("");
for (int i = 0; i<maxNumberLength - number.toString().length(); i++)
{
spaces.append(" ");
}
return spaces.toString();
}
In (4) you take number as first param (that's the number that is to be followed by spaces) and maxNumberLength from (3). This way all of your numbers would take the same amount of spaces in the output. I build the spaces with StringBuilder which is more effective for String concatenation.
So that's it - two changes and it should work.
I attach my full code so if you need you can test it:
public class TraingleTest
{
private final BufferedReader input;
private Integer numberOfRows;
public static void main(String args[])
{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
new TraingleTest(input).run();
}
private TraingleTest(final BufferedReader input)
{
this.input = input;
}
private void run()
{
boolean validNumber = false;
System.out.print("Please enter number of rows for Pascals Triangle: ");
do
{
String usersInput = readUserInput();
validNumber = validateInput(usersInput);
} while (!validNumber);
makeTriangle();
}
private String readUserInput()
{
try
{
return input.readLine();
}
catch (final IOException e)
{
System.out.print("Error while reading input. Please try one more time: ");
return "";
}
}
private boolean validateInput(final String input)
{
try
{
Integer inputValue = Integer.parseInt(input);
if (inputValue > 2 && inputValue < 22)
{
numberOfRows = inputValue;
return true;
}
System.out.print("Value must be an integer between 3 and 21. Please insert valid number: ");
return false;
}
catch (final Exception e)
{
System.out.print("Error while parsing input. Please insert valid number: ");
}
return false;
}
private void makeTriangle()
{
int maxNumberLength = Double.valueOf(Math.pow(2d, numberOfRows.doubleValue())).toString().length();
for(int i = 0; i < numberOfRows; i++){
String spaces = "";
int counter = (maxNumberLength*(numberOfRows - i))/2;
for(int f = counter; f > 0; f --)
{
spaces += " ";
}
System.out.print(spaces);
for(int j = 0; j <= i; j++)
{
long number = ncr(i, j);
System.out.print(number + spaces(number, maxNumberLength));
}
System.out.println();
}
}
private String spaces(final Long number, final int maxNumberLength)
{
StringBuilder spaces = new StringBuilder("");
for (int i = 0; i<maxNumberLength - number.toString().length(); i++)
{
spaces.append(" ");
}
return spaces.toString();
}
public long ncr(int n, int r)
{
return fact(n) / (fact(r) * fact(n - r));
}
public long fact(int n)
{
long ans = 1;
for(int i = 2; i <= n; i++)
{
ans *= i;
}
return ans;
}
}
// I have not inputted the rows you can just give an input statement and input no of rows
public class PascalTriangle {
public static void main(String[] args) {
int rows = 10;
for(int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%"+(rows-i)*2+"s","");
for(int j = 0; j <= i; j++) {
System.out.format("%4d",number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
this code will help you
int rows = 10;
for(int i =0;i<rows;i++) {
int number = 1;
System.out.format("%"+(rows-i)*2+"s","");
for(int j=0;j<=i;j++) {
System.out.format("%4d",number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
The simplest thing to is to decree that every number you output will use a set number of characters, and to add extra blanks if necessary when outputting each number. For example, you can decide that each number will take 4 characters (if all the numbers are 9999 or less--actually, with Pascal's triangle with 20 rows, you'll need at least 5 characters). Then you'll need to adjust the number of spaces you print out in each row of the triangle.
To convert a number to a 4-character string where the number is pushed over to the right of the 4-character "box", and you add blanks on the left if necessary, use String.format:
String output = String.format("%4d", number);
If you want the number to be at the left of the "box",
String output = String.format("%-4d", number);
If you want the number to be centered in the "box", this is harder. Here's a method that will pad a string on both sides with blanks, making the padding as close to equal on both sides as possible:
public static String center(int desiredLength, String input) {
if (input.length() >= desiredLength) {
return input;
}
int leftPadding = (desiredLength - input.length()) / 2;
int rightPadding = desiredLength - input.length() - leftPadding;
StringBuilder result = new StringBuilder();
for (int i = 0; i < leftPadding; i++) {
result.append(' ');
}
result.append(input);
for (int i = 0; i < rightPadding; i++) {
result.append(' ');
}
return result.toString();
}
and then you could say
System.out.print(center(4, Integer.toString(number)));
or, if number is a long,
System.out.print(center(4, Long.toString(number)));
(P.S. Instead of StringBuilder, you could declare result to be a String and use things like result += " " like you did in your original question. That would work just as well, except maybe a few nanoseconds slower.)
package myjavapractice;
import java.util.Arrays;
import java.util.Scanner;
public class pascaltriangle
{
public static void main(String args[]) {
int i;
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[][] pascal=new int[n][];
for(i=0;i<n;i++)
{
pascal[i]=new int[i+1];
}
pascal[0][0]=pascal[1][0]=pascal[1][1]=1;
for(int j=2;j<n;j++) {
pascal[j]=getNextRow(pascal[j]);
}
//print
for(int k=0;k<n;k++)
{
System.out.println(Arrays.toString(pascal[k]));
}
}
static int[] getNextRow(int[] p)
{
int[] current = new int[p.length];//row
System.out.println("length "+p.length);
current[0]=current[current.length-1]=1;//colmn
for(int m=1;m<current.length-1;m++)
{
current[m]=p[m]+p[m-1];
System.out.println("pof m is"+p[m]);
}``
return current;
}
}

Nested for loop sum of integers

public class NestedCountLoop
{
public static void main(String[] args)
{
int sum = 0;
for (int i = 1; sum < 5050; i++) {
sum = sum + i;
System.out.println(sum);
}
}
}
So I have a little homework assignment for my intro programming class to use a nested loop to accept positive integer input and add all of the integers within the interval from 1 to that input. My mind is playing games with me and I'm having trouble getting going. I know I need a scanner and whatnot, and it has to print every result from 1 to n such as "The sum of 1 to 100 is 5050." Any advice is helpful
Information on scanner at from http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Scanner sc = new Scanner(System.in);
for (int i = o; i < 100; i++){
int upperLimit = sc.nextInt();
for (int w = 0; w < upperLimit; w++){
sum = sum + i;
}
System.out.println("Sum is " + sum);
}
public class NestedCountLoop
{
public static void main(String[] args)
{
int to = Integer.parseInt(args[0]);
int sum = 0;
for (int i = 1; sum < to; i++) {
sum = sum + i;
System.out.println(sum);
}
}
}
How about this one? It takes an input from the command line (arg0), and adds every number to your number (not inclusive).
So you have to compile your java file with javac, then you can run:
javac NestedCountLoop.java
java NestedCountLoop.class 100
On the other hand, the a previous solution mentioned the javadoc for your scanner, if you really need to use it. :)
System.out.println("Enter your maximum number: ");
// get the input
Scanner input = new Scanner(System.in);
int max = input.nextInt();
int sum = 0;
// iterate through an array to sum up the numbers
for (int i = 1; i < max; i++) {
sum = sum + i; // sum += i;
}
// print out the sum after you counted everything
System.out.println(sum);
import java.util.Scanner;
public class sumoftenIntegerInput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
for(int i=1; i<=10; i++){
System.out.println("Enter integer input " + i + ":");
int a = input.nextInt();
sum = sum + a ;
}
System.out.println("Total is:" + sum );
}
}

Categories