Extract the last 2 digits of an integer (Java) - java

I have some code that takes an integer and extracts the last 2 numbers and prints them. For example, if I input 10000001, 01 should be the printout/ output. The problem here is that for some reason the output of the program is 1. I am not sure why the output shows up as a single digit.
public class Main {
public static void main(String[] args) {
double num = 10000001;
double digit = num % 100;
System.out.println(digit);
}
}

Your problem is simple and has a simple answer.
In java int num = 1; is same as int num = 01; (both mean same 1 for the compiler) so when you are using % 100 with your number it returns 01 which is nothing but 1 for java as you are storing it to a double data type variable (actually when you use double in this line double digit = num % 100; it prints 1.0 , so you should use int here int digit = num % 100; to remove the decimal point).
So using int digit = num % 100; will work and give you desired results with all number except numbers having a 0 before a number.
To solve your problem completely you can use String class.
String str = num+""; //connverting int to string
String digit = str.substring(str.length()-2, str.length());

This is because your calculated value is "01". which while display java is considering it as "1". You can use padding but have to convert that integer to a string.
public static void main(String []args){
double num = 10000001;
int digit =(int) num%100;
String padding =String.format("%02d",digit);
System.out.println(padding);
}
Or If you are taking binary numbers better to use string and then displaying last two numbers using length() on string.

Another method you can try out is extracting the last two digits and printing as string.
int num = 10001;
int last_digit = num % 10; // extract the last digit
num /= 10; // modify the original number
int second_to_last_digit = num % 10; // extract second last digit
String str = String.valueOf(second_to_last_digit) + String.valueOf(last_digit); // convert and add strings
System.out.println(str); // print desired string

Related

Putting the Digits of an int into an Array using Java?

I want to separate int values that are provided via user input. For example, when entering 153 I want to extract each digit (3 then 5 then 1 or vice versa) and stick all of them into an int[].
So far I have used the modulus operator to extract the last digit, but I still need to extract all the previous digits so I can proceed to test whether the int given by the user is narcissistic or not.
The reason for doing this is so that I can test whether the user has inputted a narcissistic number. The program will return true or false depending on the input.
public class narc {
public static void main(String[] args){
Scanner myScan = new Scanner(System.in);
System.out.println("enter number: ");
int digit = myScan.nextInt();
String s1 = Integer.toString(digit);
System.out.println(narcNumber(digit));
}
public static boolean narcNumber(int number) {
System.out.println(number%10);
return false;
}
}
So far, narcNumber(num) only returns the last digit of the given number.
int[] split = new int[s1.length()];
for (int i = 0; i < split.length; i++) {
split[i] = Character.getNumericValue(s1.charAt(i));
}
split will contain all numbers of the input number.
If you still want to use modulus to get the digits :
List<Integer> digits = new ArrayList<Integer>();
while(inputNumber > 0) {
currentDigit = inputNumber % 10;
digits.add(currentDigit);
inputNumber = inputNumber / 10;
}

(Java)Why does my decimal to binary conversion method only work some of the time when counting consecutive integers in a character array?

I'm a novice Java coder working on a problem dealing with counting consecutive integers in the binary forms of numbers.
The numbers are read from the input, and converted to binary using the method called conversion. The binary form is then sent to a character array where the for loop checks for consecutive characters(specifically the number 1) and prints the maximum count as the final answer.
I've managed to get the code to a state where I feel it should be working, but I've only had success with about half of the test cases. The larger number conversions like 262,141 tend to produce incorrect answers. Can anyone tell me where I've gone wrong?
I have a suspicion that it's something to do with the character array, but after several hours of research I haven't been able to find a solution to my particular problem.
import java.io.*;
import java.util.*;
public class Solution {
public static int conversion(int decimal){//this will take the decimal from the input and convert it to binary
int result = 0;//the result from each step of the conversion
int base = 1;//used to multiply the remainder by 1, 10, 100 etc
while(decimal > 0){
int remainder = decimal % 2;//takes the remainder of the iteration
decimal = decimal / 2;//halves the decimal number
result = result + (remainder * base);//pseudo concatenation of the binary
base = base * 10;//increases the base multiplier to continue filling out the binary leftward
}
return result;//returns result after loop has finished
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();//scan the input to obtain the decimal number
int binaryForm = conversion(n);//convert the decimal to binary and assign to binaryForm variable
String stringForm = Integer.toString(binaryForm);//convert binaryForm to a String
int counter = 1;
int max = 1;
char testArray[] = stringForm.toCharArray();//send stringForm to fill out testArray
for(int i = 0; i < testArray.length - 1; i++){//loops through testArray to test stringForm values
if(testArray[i] == testArray[i + 1] && testArray[i] == '1'){//if consecutive values equal char 1, increase counter
counter += 1;
if(counter > max){
max = counter;//if counter is higher than current maxCounter, increase maxCounter
}
}
else {//if consecutive values do not equal 1, reset counter
counter = 1;
}
}
System.out.print(max);//print the maximum consecutive values for the decimal input when converted to binary
}
}
You are trying to create a binary representation of a decimal number using an integer. This will work for smaller numbers but it doesn't take long for you to reach an overflow. You should use a string representation of the binary number like so
String numBin = "";
while(num > 0)
{
numBin = num % 2 + numBin;
num = num / 2;
}
System.out.println("Binary Representation: " + numBin);
Then take that string and loop through it calculating the consecutive counts of 1's
int consecutiveCount = 0;
for(int i = 0; i < numBin.length() - 1; i++)
{
if(numBin.charAt(i) == '1' && numBin.charAt(i + 1) == '1')
{
consecutiveCount++;
}
}
System.out.println("Consecutive Count: " + consecutiveCount);
Output
Number: 261141
Binary Representation: 111111110000010101
Consecutive Count: 7
Number: 3
Binary Representation: 11
Consecutive Count: 1
Number: 18
Binary Representation: 10010
Consecutive Count: 0
Number: 1111111
Binary Representation: 100001111010001000111
Consecutive Count: 5

How to concatenate seperate digits from a loop into one single integer

okay so I have an assignment that says i have a string of numbers for example
"1234 4014 5555 7654" say which is essentially a credit card number.
They are asking me to convert the string of digits into single integers then concatenate them into 4 lots of 4 digit integers so the string "1234 4014 555 7654" for example will have 4 blocks
block 1 would be 1234
which is converted into 1, 2, 3, 4
which is then concatenated into 1234 as an integer
i have to do this for all the blocks... :(
So far.. i made a for loop as shown below :
public static int toInt(String digitString)
{
int answer = 0;
int num = 0;
for (int j = 0; j < digitString.length(); j++){
num = (int) digitString.charAt(j) - '0';
System.out.println(num);
}
return answer
}
and i can successfully convert the string into seperate digits but i have no idea how i can concatenate those digits into 4, 4 digit integers
any help would be much appreciated :)
I'm not going to do your assignment for you, but I'll tell you this hint: All you need to know to understand and solve this problem is that Integer.parseInt(s) for some String s returns s as an integer, and that s.substring(n, n+1) returns the (n+1)st character of a String.
For example
String s = "1234";
s = s.substring(0, 1); //s = "1"
int val = Integer.parseInt(s); //val = 1
And that's it. Now it's just a matter of looping over your String and doing whatever you want with them. I suppose it might be helpful to know that you can assign an integer to a string with:
String temp = val + "";
//or
String temp = String.valueOf(val);

Iterate through each digit in a number

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

Retrieving the first digit of a number [duplicate]

This question already has answers here:
Return first digit of an integer
(25 answers)
Closed 5 years ago.
I am just learning Java and am trying to get my program to retrieve the first digit of a number - for example 543 should return 5, etc. I thought to convert to a string, but I am not sure how I can convert it back? Thanks for any help.
int number = 534;
String numberString = Integer.toString(number);
char firstLetterChar = numberString.charAt(0);
int firstDigit = ????
Almost certainly more efficient than using Strings:
int firstDigit(int x) {
while (x > 9) {
x /= 10;
}
return x;
}
(Works only for nonnegative integers.)
int number = 534;
int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
firstDigit = number/((int)(pow(10,(int)log(number))));
This should get your first digit using math instead of strings.
In your example log(543) = 2.73 which casted to an int is 2.
pow(10, 2) = 100
543/100 = 5.43 but since it's an int it gets truncated to 5
int firstDigit = Integer.parseInt(Character.toString(firstLetterChar));
int number = 534;
String numberString = "" + number;
char firstLetterchar = numberString.charAt(0);
int firstDigit = Integer.parseInt("" + firstLetterChar);
Integer.parseInt will take a string and return a int.
This example works for any double, not just positive integers and takes into account negative numbers or those less than one. For example, 0.000053 would return 5.
private static int getMostSignificantDigit(double value) {
value = Math.abs(value);
if (value == 0) return 0;
while (value < 1) value *= 10;
char firstChar = String.valueOf(value).charAt(0);
return Integer.parseInt(firstChar + "");
}
To get the first digit, this sticks with String manipulation as it is far easier to read.
int number = 534;
int firstDigit = number/100;
( / ) operator in java divide the numbers without considering the reminder so when we divide 534 by 100 , it gives us (5) .
but if you want to get the last number , you can use (%) operator
int lastDigit = number%10;
which gives us the reminder of the division , so 534%10 , will yield the number 4 .
This way might makes more sense if you don't want to use str methods
int first = 1;
for (int i = 10; i < number; i *= 10) {
first = number / i;
}

Categories