I want to read a number as a String, and split its characters to an integer array, and find the sum of it's digits by looping through that integers array.
This is my code so far:
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
String Number = S.next();
int counterEnd = Number.length();
int sum = 0 ;
for ( int i = 0 ; i < counterEnd ; i++) {
sum += sum + (Number.charAt(i));
}
System.out.println(sum);
}
Unfortunately, this code prints the sum of ASCII not the digits.
You can subtract the '0' character (i.e. '1' - '0' is 49 - 48 = 1):
sum += Number.charAt(i) - '0';
You could, has #August suggested, substract the character '0' to obtain the numeric value of the character (I find this approach kind of hackish). Or you can use Character.getNumericValue to achieve this:
sum += Character.getNumericValue(Number.charAt(i)); //note it's sum += theDigit; not sum += sum + theDigit
You might also want to look at the enhanced for loop, as you basically don't need the index here:
for(char c : Number.toCharArray()) {
sum += Character.getNumericValue(c);
}
As of Java 8 you could also do it like this:
int sum = Number.chars().map(Character::getNumericValue).sum();
It basically gets a Stream of the characters in the String, map each character to its corresponding numeric value and sum them.
sum+= Integer.parseInt(String.valueOf(Number.charAt(i)));
You can do it like this:
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
String n = S.next();
int sum = 0;
for (int i = 0; i < n.length(); i++) {
sum += Integer.parseInt(n.substring(i, i+1));
}
System.out.println(sum);
}
Note: Replacing the body of the for loop with:
int offset = (n.substring(i, i+1).equals("-")) ? 1 : 0;
sum += Integer.parseInt(n.substring(i, i+1+offset));
i+=offset;
Will allow the program to take negative numbers. Ex: Inputting
-24
Would return a positive 2.
Related
I am trying to find the number of consecutive 1's in a binary.
Example: Convert Decimal number to Binary and find consecutive 1's
static int count = 0;
static int max = 0;
static int index = 1;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.close();
String b = Integer.toBinaryString(n);
char[] arr = b.toCharArray();
System.out.println(arr);
for (int i = 0; i < b.length(); i++) {
if (arr[i] == index) {
count++;
} else {
count = 0;
}
if (count > max) {
max = count;
}
}
System.out.println(max);
}
I am always getting 0. It seems as if the condition is not working in my code. Could you please provide your suggestion on where am I going wrong with this?
Your qusetion is not so clear but AFAIU from your algorithm, you're trying to find number of most repeated 1's. The issue is that when you're doing comparision if (arr[i] == index), the comparison is done with a char and integer because type of arr is char array. Isn't it? To overcome it either you can convert the char array into integer or convert the integer index value into char. I do this to overcome it.
if (arr[i] == index + '0')
It is not an really elegant solution. I assume that you're a student and want you to show what's wrong. If I want to do something like this, I use,
private static int maxConsecutiveOnes(int x) {
// Initialize result
int count = 0;
// Count the number of iterations to
// reach x = 0.
while (x!=0) {
// This operation reduces length
// of every sequence of 1s by one.
x = (x & (x << 1));
count++;
}
return count;
}
Its trick is,
11101111 (x)
& 11011110 (x << 1)
----------
11001110 (x & (x << 1))
^ ^
| |
trailing 1 removed
As I understand correctly, you want to count maximum length of the group of 1 in the binary representation of the int value. E.g. for 7917=0b1111011101101 result will be 4 (we have following groups of 1: 1, 2, 3, 4).
You could use bit operations (and avoid to string convertation). You have one counter (to count amount of 1 in the current group) and max with maximum of all such amounts. All you need is just to check lowest bit for 1 and then rotate value to the right until it becomes 0, like getMaxConsecutiveSetBit1.
Or just do it in a very simple way - convert it to the binary string and count amount of 1 characters in it, like getMaxConsecutiveSetBit2. Also have one counter + max. Do not forget, that char in Java is an int on the JVM level. So you do not have compilation problem with compare char with int value 1, but this is wrong. To check if character is 1, you have to use character - '1'.
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
int val = scan.nextInt();
System.out.println(Integer.toBinaryString(val));
System.out.println(getMaxConsecutiveSetBit1(val));
System.out.println(getMaxConsecutiveSetBit2(val));
}
}
public static int getMaxConsecutiveSetBit1(int val) {
int max = 0;
int cur = 0;
while (val != 0) {
if ((val & 0x1) != 0)
cur++;
else {
max = Math.max(max, cur);
cur = 0;
}
val >>>= 1;
}
return Math.max(max, cur);
}
public static int getMaxConsecutiveSetBit2(int val) {
int max = 0;
int cur = 0;
for (char ch : Integer.toBinaryString(val).toCharArray()) {
if (ch == '1')
cur++;
else {
max = Math.max(max, cur);
cur = 0;
}
}
return Math.max(max, cur);
}
Change type of index variable from int to char:
static char index = 1;
to let the comparison made in this line:
if (arr[i] == index)
do its job. Comparing int 1 (in your code this is the value stored in index variable) with char '1' (in your example it's currently checked element of arr[]) checks if ASCII code of given char is equal to int value of 1. This comparison is never true as char '1' has an ASCII code 49 and this is the value that is being compared to value of 1 (49 is never equal to 1).
You might want to have a look at ASCII codes table in the web to see that all characters there have assigned corresponding numeric values. You need to be aware that these values are taken into consideration when comparing char to int with == operaror.
When you change mentioned type of index to char, comparison works fine and your code seems to be fixed.
Using your for loop structure and changing a few things around while also adding some other stats to report which could be useful. I count the total number of 1's in the number, the number of consecutive 1's (groups of 1's), and the greatest number of consecutive 1's. Also your for loop was looping based on the string length and not the array's length which is just sort of nit picky. Here is the code
int count = 0;
int max = 0;
char index = '1';
int consecutiveOnePairs = 0;
int numberOfOnes = 0;
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String b = Integer.toBinaryString(n);
char[] arr = b.toCharArray();
System.out.println(arr);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == index)
{
count++;
numberOfOnes++;
}
if((i + 1 == arr.length && count > 1) || arr[i] != index)
{
if(count > 1)
consecutiveOnePairs++;
if (count > max)
max = count;
count = 0;
}
}
System.out.println("Total Number of 1's in " + n + " is " + numberOfOnes);
System.out.println("Total Number of Consecutive 1's in " + n + " is " + consecutiveOnePairs);
System.out.println("Greatest Number of Consecutive 1's in " + n + " is " + max);
scan.close();
Output
13247
11001110111111
Total Number of 1's in 13247 is 11
Total Number of Consecutive 1's in 13247 is 3
Greatest Number of Consecutive 1's in 13247 is 6
511
111111111
Total Number of 1's in 511 is 9
Total Number of Consecutive 1's in 511 is 1
Greatest Number of Consecutive 1's in 511 is 9
887
1101110111
Total Number of 1's in 887 is 8
Total Number of Consecutive 1's in 887 is 3
Greatest Number of Consecutive 1's in 887 is 3
If you use Java 8, you can try this snippet:
public int maxOneConsecutive(int x)
{
String intAsBinaryStr = Integer.toBinaryString(x);
String[] split = intAsBinaryStr.split("0");
return Arrays.stream(split)
.filter(str -> !str.isEmpty())
.map(String::length)
.max(Comparator.comparingInt(a -> a)).orElse(0);
}
Currently going through an exercise in my book, but i'm stuck ( I havent learned arrays yet, this chapter is on loops nested loops and for loops)
The first part of the problem is to take a credit card number and then sum every other number backwards
Consider 4358 9795, which should output the sum 5+7+8 + 3 = 23.
Heres my solution which isn't working
class Checkit{
private String creditNum;
private int sum;
public Checkit(String creditNum)
{
this.creditNum = creditNum;
sum = 0;
}
public int getSum()
{
for (int i = creditNum.length() ; i > 0 ; i--)
{
char ch = creditNum.charAt(i-1);
if(i%2 == 1 )
{
sum+=ch;
}
}
return sum;
}
}
public class test{
public static void main(String [] args)
{
Checkit sampleNumber = new Checkit("4358 9795");
System.out.println(sampleNumber.getSum());
}
}
I'm not exactly sure whats wrong with my logic. ch is taking all of the values of my credit card number 5,7,8,3. But for some reason the sum is messing up.
BONUS PART
Take Each number that wasn't added and double it, so 9+9 + 5 + 4, double each of those terms ( that becomes 18 + 18 + 10 + 8), and then get the sum of 1 + 8 + 1 + 8 + 1 + 0 + 8.
I tried the bonus part, but for some reason every time I get 9, 9, 5,4 and times that char value by 2, I get letters. I don't think I can multiply chars by integers, so should I do conversions? Note I didn't learn arrays yet
NEW CODE
class Checkit {
private String creditCardNum;
private int sum;
public Checkit(String creditCardNum) {
sum = 0;
this.creditCardNum = creditCardNum;
}
public int getSum() {
creditCardNum = creditCardNum.replaceAll("\\s+", "");
for (int i = creditCardNum.length(); i > 0; i--) {
char ch = creditCardNum.charAt(i - 1);
if (i % 2 == 0) {
sum += Character.getNumericValue(ch);
}
}
return sum;
}
public int doubleDigitSum() {
sum = 0;
creditCardNum = creditCardNum.replaceAll("\\s", "");
for (int i = creditCardNum.length(); i > 0; i--) {
char ch = creditCardNum.charAt(i - 1);
if (i % 2 == 1) {
int newChar = Character.getNumericValue(ch) * 2;
String newCharString = Integer.toString(newChar);
for (int j = 0; j < newCharString.length(); j++) {
char sumThis = newCharString.charAt(j);
sum += Character.getNumericValue(sumThis);
}
}
}
return sum;
}
}
public class DataSet{
public static void main(String [] args) {
Checkit data = new Checkit("4358 9795");
System.out.println(data.getSum());
System.out.println(data.doubleDigitSum());
}
}
You're adding char values rather than int values. Replace sum+=ch; with
sum += ch - '0';
The reason why this works as opposed to the original solution is that when you're adding char values to an int value, the char is converted to a decimal via its ASCII value. For example, '5' has a ASCII dec value of 53. However, '5' - '0' equals 5. More on these ASCII values can be found here, http://www.asciitable.com/
Your issue is that you are not converting the char to an integer:
public int getSum()
{
for (int i = creditNum.length() ; i > 0 ; i--)
{
char ch = creditNum.charAt(i-1);
if(i%2 == 1 )
{
sum+=ch;
}
}
return sum;
}
Fun fact that's causing your error - chars are numbers! They're simply a number that represents the ascii character code of the letter. So when you add them to a sum, Java is OK with that and just adds the corresponding number for the char '8' for example, which is 56.
To make your code work, you need to properly convert to an integer:
public int getSum()
{
for (int i = creditNum.length() ; i > 0 ; i--)
{
char ch = creditNum.charAt(i-1);
if(i%2 == 1)
{
sum+=Character.getNumericValue(ch);
}
}
return sum;
}
for (int i = creditNum.length() ; i > 0 ; i--) {
char ch = creditNum.charAt(i-1);
First iteration thru loop gets IndexOutOfBounds exception. And then you never check the initial character of the credit card number, since your termination criterion is ( i > 0 ), not (i >= 0)
And why not just use i -= 2 for the increment instead of the if-check?
Sorry if the title is misleading or is confusing, but here is my dilemma.
I am inputting a string, and want to assign a value to each capitalized letter in the alphabet (A=1, .. Z=26) and then add the values of each letter in that string.
Example: ABCD = 10 (since 1 + 2 + 3 + 4)
But I don't know how to add all the values in the string
NOTE: This is only for capitalized letters and strings
public class Test {
public static void main(String[] args) {
Scanner scannerTest = new Scanner(System.in);
System.out.println("Enter a name here: ");
String str = scannerTest.nextLine();
char[] ch = str.toCharArray();
int temp_integer = 64;
for (char c : ch) {
int temp = (int) c;
if (temp <= 90 & temp >= 65){
int sum = (temp - temp_integer);
System.out.println(sum);
}
}
}
}
So, as you can see I print out the sum for each time its looped,
meaning: if I input "AB", the output will be 1 and 2.
However, I want to go a step further, and add these two values together, but I'm stumped, any suggestions or help? (NOTE: this is not a assignment or anything, just practising problem sets)
I would prefer to use the character literals. You know that the range is A to Z (1 to 26), so you can subtract 'A' from each char (but you need to add 1 because it doesn't start at 0). I would also call toUpperCase on the input line. Something like,
Scanner scannerTest = new Scanner(System.in);
System.out.println("Enter a name here: ");
String str = scannerTest.nextLine().toUpperCase();
int sum = 0;
for (char ch : str.toCharArray()) {
if (ch >= 'A' && ch <= 'Z') {
sum += 1 + ch - 'A';
}
}
System.out.printf("The sum of %s is %d%n", str, sum);
Which I tested with your example
Enter a name here:
ABCD
The sum of ABCD is 10
Using 64 to represent the character before 'A' in the ascii table is difficult to understand, you can perform substration between characters in Java directly.
So if 'A' represent 1, then just do c - 'A' + 1 will give you the corresponding integer value for each capitalized letter.
To get the sum, just sum up: initialize the sum as 0, and in the for loop, add increment sum by the value you calculated. You can use the incremental assignment operation: +=
Scanner scannerTest = new Scanner(System.in);
System.out.println("Enter a name here: ");
String str = scannerTest.nextLine();
char[] ch = str.toCharArray();
int sum = 0;
for (char c : ch) {
sum += c - 'A' + 1;
}
System.out.println(sum);
Change only your for to these:
int sum = 0;
for(int i = 0; i < ch.length; i++){
sum += (int) ch[i] - 96;
System.out.println(sum);
}
The sum += (int) ch[i] - 96; is because the char a is the value 97, as your say, you want char a corresponde to 1, note that a is different than A
Check the char value here: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
This was tested and worked fine! Good Luck
It would look something like this (in C programming language) which you can easily modify for other programming languages:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int i;
char word[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
unsigned int sum = 0;
unsigned int charVal;
for (i=0; i < strlen(word); ++i) {
charVal = word[i] - 'A' + 1;
printf("Value of %c is %d\n", word[i], charVal);
sum += charVal;
}
printf("Sum of %s = %d\n", word, sum);
return(0);
}
The trick is to take the character value, subtract the baseline 'A' value and add 1 to arrive at your calculation range:
charVal = word[i] - 'A' + 1;
Achieve the same in a concise way by employing Java 8's lambda functions
String str = "ABCD";
int sum = str.chars()
.filter(c -> c >= 'A' && c <= 'Z')
.map(c -> 1 + c - 'A')
.reduce(0, Integer::sum);
Im trying to determine whether the number is odd or even, the length of the input and the sum of all the digits in the input.
Heres my attempt:
public static int statNum(int input) {
if(input % 2 == 0) {
System.out.println("The number is even");
} else {
System.out.println("The number is odd");
}
System.out.println(Integer.toString(input).length());
String number = String.valueOf(input);
char [] values = number.toCharArray();
int sum = 0;
for (int i = 0; i < values.length; i++) {
sum = sum + values[i];
}
System.out.println("The sum of this number is: " + sum);
return input;
}
If i input 1 the sum is equal to 49, if I input 1234 the input is equal to 202. What am I doing wrong?
You are adding char values i.e adding the ASCII value of the char to the sum, You should parse them to int before adding
Do this
sum = sum + Integer.parseInt(Character.toString(values[i]));
or as #ZouZou suggested, can use
sum = sum + Character.getNumericValue(values[i]);
You need to subtract the char value '0', so you're only adding the numeric value above zero, rather than adding the value of the char itself (which is its ascii character value):
sum = sum + values[i] - '0';
Following is a code to find sum of digits of a number & length of number :
int sum=0;
int length=0;
while(input!=0)
{
sum+=input%10;
input/=10;
length++;
}
I am trying to create a program that will tell if a number given to it is a "Happy Number" or not. Finding a happy number requires each digit in the number to be squared, and the result of each digit's square to be added together.
In Python, you could use something like this:
SQUARE[d] for d in str(n)
But I can't find how to iterate through each digit in a number in Java. As you can tell, I am new to it, and can't find an answer in the Java docs.
You can use a modulo 10 operation to get the rightmost number and then divide the number by 10 to get the next number.
long addSquaresOfDigits(int number) {
long result = 0;
int tmp = 0;
while(number > 0) {
tmp = number % 10;
result += tmp * tmp;
number /= 10;
}
return result;
}
You could also put it in a string and turn that into a char array and iterate through it doing something like Math.pow(charArray[i] - '0', 2.0);
Assuming the number is an integer to begin with:
int num = 56;
String strNum = "" + num;
int strLength = strNum.length();
int sum = 0;
for (int i = 0; i < strLength; ++i) {
int digit = Integer.parseInt(strNum.charAt(i));
sum += (digit * digit);
}
I wondered which method would be quickest to split up a positive number into its digits in Java, String vs modulo
public static ArrayList<Integer> splitViaString(long number) {
ArrayList<Integer> result = new ArrayList<>();
String s = Long.toString(number);
for (int i = 0; i < s.length(); i++) {
result.add(s.charAt(i) - '0');
}
return result; // MSD at start of list
}
vs
public static ArrayList<Integer> splitViaModulo(long number) {
ArrayList<Integer> result = new ArrayList<>();
while (number > 0) {
int digit = (int) (number % 10);
result.add(digit);
number /= 10;
}
return result; // LSD at start of list
}
Testing each method by passing Long.MAX_VALUE 10,000,000 times, the string version took 2.090 seconds and the modulo version 2.334 seconds. (Oracle Java 8 on 64bit Ubuntu running in Eclipse Neon)
So not a lot in it really, but I was a bit surprised that String was faster
In the above example we can use:
int digit = Character.getNumericValue(strNum.charAt(i));
instead of
int digit = Integer.parseInt(strNum.charAt(i));
You can turn the integer into a string and iterate through each char in the string. As you do that turn that char into an integer
This code returns the first number (after 1) that fits your description.
public static void main(String[] args) {
int i=2;
// starting the search at 2, since 1 is also a happy number
while(true) {
int sum=0;
for(char ch:(i+"").toCharArray()) { // casting to string and looping through the characters.
int j=Character.getNumericValue(ch);
// getting the numeric value of the current char.
sum+=Math.pow(j, j);
// adding the current digit raised to the power of itself to the sum.
}
if(sum==i) {
// if the sum is equal to the initial number
// we have found a number that fits and exit.
System.out.println("found: "+i);
break;
}
// otherwise we keep on searching
i++;
}
}