How to add numbers(integers) that are stored inside a string - java

I have to create a program that uses Luhn's algorithm to check to see if a credit card is valid.
The algorithm is this:
Form a sum of every other digit, including the right-most digit; so
5490123456789128 sums to 8+1+8+6+4+2+0+4 = 33
Form double each remaining digit, then sum all the digits that creates it; the remaining digits in our example (5 9 1 3 5 7 9 2) double to 10 18 2 6 10 14 18 4, which sums to 1+0+1+8+2+6+1+0+1+4+1+8+4 = 37
Add the two sums above (33+37 = 70)
If the result is a multiple of 10 (i.e., its last digit is 0) then it was a valid credit card number.
I made a Scanner and saved the credit card number into String card number
Then I created a while loop to save every other character starting from the right into a string. So now, I have a string filled with every other digit of the credit card number, starting from the right. However, I need to add up all of the digits within that string, which I can't figure out.
For example, if the user entered 1234 as the card number, the string everyotherdigit = 42. How can I add up 4 and 2 within the string?

There are numerous ways to do that. You can actually find your own solution by doing a bit of googling.
Anyway, this is what you can do:
Get individual characters from your string, and convert them to int.
String cardNumber = "5490123456789128";
int value = cardNumber.charAt(0) - '0';
Using a for loop and changing 0 to x(loop counter) will solve everything.
Get single String and convert to int.
String cardNumber = "5490123456789128";
int value = Integer.parseInt(cardNumber.substring(0,1));

I'd treat the string as an array of chars, and use Character.digit(int, int) to convert each character to the corresponsing int:
public static boolean isValidCreditCard (String s);
char[] arr = s.toCharArray();
int everyOtherSum = 0;
for (int i = arr.length - 1; i >= 0; i -= 2) {
everyOtherSum += Character.digit(arr[i], 10);
}
int doubleSum = 0;
for (for (int i = arr.length - 2; i >= 0; i -= 2) {
int currDigit = Character.digit(arr[i], 10);
int doubleDigit = currDigit * 2;
while (doubleDigit > 0) {
doubleSum += (doubleDigit % 10);
doubleDigit /= 10;
}
}
int total = everyOtherSum + doubleSum;
return total % 10 == 0;
}

So something like this would work for you:
public static void main(String[] args)
{
String cardNum = "5490123456789128";
String others = null;
int evenDigitSum = 0;
int oddDigitTransformSum = 0;
for (int pos = 0; pos < cardNum.length(); pos++)
{
if ((pos%2) != 0)
{
evenDigitSum += (cardNum.charAt(pos) - '0');
}
else
{
others = Integer.toString((cardNum.charAt(pos)-'0')*2);
for (char c : others.toCharArray())
{
oddDigitTransformSum += (c-'0');
}
}
}
System.out.println("Odds: " + oddDigitTransformSum);
System.out.println("Evens: " + evenDigitSum);
System.out.println("Total: " + (evenDigitSum+oddDigitTransformSum));
System.out.println("Valid Card: " + ((evenDigitSum+oddDigitTransformSum)%10==0));
}

public int cardCount(String numbers){
Stack<Integer> stack = new Stack<>();
int count = 0;
for(char c : numbers.toCharArray()){
stack.push(Character.getNumericValue(c));
}
int size = stack.size();
for(int i=1;i <= size; i++){
if(i%2 != 0){
count = count + stack.pop();
}else{
stack.pop();
}
}
return count;
}
This just does what you asked, not the entire algorithm

Related

How do I swap all the digits of input number(From first to last, from second to last second and so on, Pseudocode would be good) [duplicate]

I have numbers like 1100, 1002, 1022 etc. I would like to have the individual digits, for example for the first number 1100 I want to have 1, 1, 0, 0.
How can I get it in Java?
To do this, you will use the % (mod) operator.
int number; // = some int
while (number > 0) {
print( number % 10);
number = number / 10;
}
The mod operator will give you the remainder of doing int division on a number.
So,
10012 % 10 = 2
Because:
10012 / 10 = 1001, remainder 2
Note: As Paul noted, this will give you the numbers in reverse order. You will need to push them onto a stack and pop them off in reverse order.
Code to print the numbers in the correct order:
int number; // = and int
LinkedList<Integer> stack = new LinkedList<Integer>();
while (number > 0) {
stack.push( number % 10 );
number = number / 10;
}
while (!stack.isEmpty()) {
print(stack.pop());
}
Convert it to String and use String#toCharArray() or String#split().
String number = String.valueOf(someInt);
char[] digits1 = number.toCharArray();
// or:
String[] digits2 = number.split("(?<=.)");
In case you're already on Java 8 and you happen to want to do some aggregate operations on it afterwards, consider using String#chars() to get an IntStream out of it.
IntStream chars = number.chars();
How about this?
public static void printDigits(int num) {
if(num / 10 > 0) {
printDigits(num / 10);
}
System.out.printf("%d ", num % 10);
}
or instead of printing to the console, we can collect it in an array of integers and then print the array:
public static void main(String[] args) {
Integer[] digits = getDigits(12345);
System.out.println(Arrays.toString(digits));
}
public static Integer[] getDigits(int num) {
List<Integer> digits = new ArrayList<Integer>();
collectDigits(num, digits);
return digits.toArray(new Integer[]{});
}
private static void collectDigits(int num, List<Integer> digits) {
if(num / 10 > 0) {
collectDigits(num / 10, digits);
}
digits.add(num % 10);
}
If you would like to maintain the order of the digits from least significant (index[0]) to most significant (index[n]), the following updated getDigits() is what you need:
/**
* split an integer into its individual digits
* NOTE: digits order is maintained - i.e. Least significant digit is at index[0]
* #param num positive integer
* #return array of digits
*/
public static Integer[] getDigits(int num) {
if (num < 0) { return new Integer[0]; }
List<Integer> digits = new ArrayList<Integer>();
collectDigits(num, digits);
Collections.reverse(digits);
return digits.toArray(new Integer[]{});
}
I haven't seen anybody use this method, but it worked for me and is short and sweet:
int num = 5542;
String number = String.valueOf(num);
for(int i = 0; i < number.length(); i++) {
int j = Character.digit(number.charAt(i), 10);
System.out.println("digit: " + j);
}
This will output:
digit: 5
digit: 5
digit: 4
digit: 2
I noticed that there are few example of using Java 8 stream to solve your problem but I think that this is the simplest one:
int[] intTab = String.valueOf(number).chars().map(Character::getNumericValue).toArray();
To be clear:
You use String.valueOf(number) to convert int to String, then chars() method to get an IntStream (each char from your string is now an Ascii number), then you need to run map() method to get a numeric values of the Ascii number. At the end you use toArray() method to change your stream into an int[] array.
I see all the answer are ugly and not very clean.
I suggest you use a little bit of recursion to solve your problem. This post is very old, but it might be helpful to future coders.
public static void recursion(int number) {
if(number > 0) {
recursion(number/10);
System.out.printf("%d ", (number%10));
}
}
Output:
Input: 12345
Output: 1 2 3 4 5
simple solution
public static void main(String[] args) {
int v = 12345;
while (v > 0){
System.out.println(v % 10);
v /= 10;
}
}
// could be any num this is a randomly generated one
int num = (int) (Math.random() * 1000);
// this will return each number to a int variable
int num1 = num % 10;
int num2 = num / 10 % 10;
int num3 = num /100 % 10;
// you could continue this pattern for 4,5,6 digit numbers
// dont need to print you could then use the new int values man other ways
System.out.print(num1);
System.out.print("\n" + num2);
System.out.print("\n" + num3);
Since I don't see a method on this question which uses Java 8, I'll throw this in. Assuming that you're starting with a String and want to get a List<Integer>, then you can stream the elements like so.
List<Integer> digits = digitsInString.chars()
.map(Character::getNumericValue)
.boxed()
.collect(Collectors.toList());
This gets the characters in the String as a IntStream, maps those integer representations of characters to a numeric value, boxes them, and then collects them into a list.
Java 9 introduced a new Stream.iterate method which can be used to generate a stream and stop at a certain condition. This can be used to get all the digits in the number, using the modulo approach.
int[] a = IntStream.iterate(123400, i -> i > 0, i -> i / 10).map(i -> i % 10).toArray();
Note that this will get the digits in reverse order, but that can be solved either by looping through the array backwards (sadly reversing an array is not that simple), or by creating another stream:
int[] b = IntStream.iterate(a.length - 1, i -> i >= 0, i -> i - 1).map(i -> a[i]).toArray();
or
int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length - i]).toArray();
As an example, this code:
int[] a = IntStream.iterate(123400, i -> i > 0, i -> i / 10).map(i -> i % 10).toArray();
int[] b = IntStream.iterate(a.length - 1, i -> i >= 0, i -> i - 1).map(i -> a[i]).toArray();
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
Will print:
[0, 0, 4, 3, 2, 1]
[1, 2, 3, 4, 0, 0]
Easier way I think is to convert the number to string and use substring to extract and then convert to integer.
Something like this:
int digits1 =Integer.parseInt( String.valueOf(201432014).substring(0,4));
System.out.println("digits are: "+digits1);
ouput is
2014
I wrote a program that demonstrates how to separate the digits of an integer using a more simple and understandable approach that does not involve arrays, recursions, and all that fancy schmancy. Here is my code:
int year = sc.nextInt(), temp = year, count = 0;
while (temp>0)
{
count++;
temp = temp / 10;
}
double num = Math.pow(10, count-1);
int i = (int)num;
for (;i>0;i/=10)
{
System.out.println(year/i%10);
}
Suppose your input is the integer 123, the resulting output will be as follows:
1
2
3
Here is my answer, I did it for myself and I hope it's simple enough for those who don't want to use the String approach or need a more math-y solution:
public static void reverseNumber2(int number) {
int residual=0;
residual=number%10;
System.out.println(residual);
while (residual!=number) {
number=(number-residual)/10;
residual=number%10;
System.out.println(residual);
}
}
So I just get the units, print them out, substract them from the number, then divide that number by 10 - which is always without any floating stuff, since units are gone, repeat.
Java 8 solution to get digits as int[] from an integer that you have as a String:
int[] digits = intAsString.chars().map(i -> i - '0').toArray();
neither chars() nor codePoints() — the other lambda
String number = Integer.toString( 1100 );
IntStream.range( 0, number.length() ).map( i -> Character.digit( number.codePointAt( i ), 10 ) ).toArray(); // [1, 1, 0, 0]
Why don't you do:
String number = String.valueOf(input);
char[] digits = number.toCharArray();
Try this one.
const check = (num) => {
let temp = num
let result = []
while(temp > 0){
let a = temp%10;
result.push(a);
temp = (temp-a)/10;
}
return result;
}
check(98) //[ 8, 9 ]
public int[] getDigitsOfANumber(int number) {
String numStr = String.valueOf(number);
int retArr[] = new int[numStr.length()];
for (int i = 0; i < numStr.length(); i++) {
char c = numStr.charAt(i);
int digit = c;
int zero = (char) '0';
retArr[i] = digit - zero;
}
return retArr;
}
Integer.toString(1100) gives you the integer as a string. Integer.toString(1100).getBytes() to get an array of bytes of the individual digits.
Edit:
You can convert the character digits into numeric digits, thus:
String string = Integer.toString(1234);
int[] digits = new int[string.length()];
for(int i = 0; i<string.length(); ++i){
digits[i] = Integer.parseInt(string.substring(i, i+1));
}
System.out.println("digits:" + Arrays.toString(digits));
This uses the modulo 10 method to figure out each digit in a number greater than 0, then this will reverse the order of the array. This is assuming you are not using "0" as a starting digit.
This is modified to take in user input.
This array is originally inserted backwards, so I had to use the Collections.reverse() call to put it back into the user's order.
Scanner scanNumber = new Scanner(System.in);
int userNum = scanNumber.nextInt(); // user's number
// divides each digit into its own element within an array
List<Integer> checkUserNum = new ArrayList<Integer>();
while(userNum > 0) {
checkUserNum.add(userNum % 10);
userNum /= 10;
}
Collections.reverse(checkUserNum); // reverses the order of the array
System.out.print(checkUserNum);
Just to build on the subject, here's how to confirm that the number is a palindromic integer in Java:
public static boolean isPalindrome(int input) {
List<Integer> intArr = new ArrayList();
int procInt = input;
int i = 0;
while(procInt > 0) {
intArr.add(procInt%10);
procInt = procInt/10;
i++;
}
int y = 0;
int tmp = 0;
int count = 0;
for(int j:intArr) {
if(j == 0 && count == 0) {
break;
}
tmp = j + (tmp*10);
count++;
}
if(input != tmp)
return false;
return true;
}
I'm sure I can simplify this algo further. Yet, this is where I am. And it has worked under all of my test cases.
I hope this helps someone.
int number = 12344444; // or it Could be any valid number
int temp = 0;
int divider = 1;
for(int i =1; i< String.valueOf(number).length();i++)
{
divider = divider * 10;
}
while (divider >0) {
temp = number / divider;
number = number % divider;
System.out.print(temp +" ");
divider = divider/10;
}
Try this:
int num= 4321
int first = num % 10;
int second = ( num - first ) % 100 / 10;
int third = ( num - first - second ) % 1000 / 100;
int fourth = ( num - first - second - third ) % 10000 / 1000;
You will get first = 1, second = 2, third = 3 and fourth = 4 ....
Something like this will return the char[]:
public static char[] getTheDigits(int value){
String str = "";
int number = value;
int digit = 0;
while(number>0){
digit = number%10;
str = str + digit;
System.out.println("Digit:" + digit);
number = number/10;
}
return str.toCharArray();
}
As a noob, my answer would be:
String number = String.valueOf(ScannerObjectName.nextInt());
int[] digits = new int[number.length()];
for (int i = 0 ; i < number.length() ; i++)
int[i] = Integer.parseInt(digits.substring(i,i+1))
Now all the digits are contained in the "digits" array.
if digit is meant to be a Character
String numstr = Integer.toString( 123 );
Pattern.compile( "" ).splitAsStream( numstr ).map(
s -> s.charAt( 0 ) ).toArray( Character[]::new ); // [1, 2, 3]
and the following works correctly
numstr = "000123" gets [0, 0, 0, 1, 2, 3]
numstr = "-123"    gets [-, 1, 2, 3]
A .NET solution using LINQ.
List<int> numbers = number.ToString().Select(x => x - 48).ToList();
I think this will be the most useful way to get digits:
public int[] getDigitsOf(int num)
{
int digitCount = Integer.toString(num).length();
if (num < 0)
digitCount--;
int[] result = new int[digitCount];
while (digitCount-- >0) {
result[digitCount] = num % 10;
num /= 10;
}
return result;
}
Then you can get digits in a simple way:
int number = 12345;
int[] digits = getDigitsOf(number);
for (int i = 0; i < digits.length; i++) {
System.out.println(digits[i]);
}
or more simply:
int number = 12345;
for (int i = 0; i < getDigitsOf(number).length; i++) {
System.out.println( getDigitsOf(number)[i] );
}
Notice the last method calls getDigitsOf method too much time. So it will be slower. You should create an int array and then call the getDigitsOf method once, just like in second code block.
In the following code, you can reverse to process. This code puts all digits together to make the number:
public int digitsToInt(int[] digits)
{
int digitCount = digits.length;
int result = 0;
for (int i = 0; i < digitCount; i++) {
result = result * 10;
result += digits[i];
}
return result;
}
Both methods I have provided works for negative numbers too.
see bellow my proposal with comments
int size=i.toString().length(); // the length of the integer (i) we need to split;
ArrayList<Integer> li = new ArrayList<Integer>(); // an ArrayList in whcih to store the resulting digits
Boolean b=true; // control variable for the loop in which we will reatrive step by step the digits
String number="1"; // here we will add the leading zero depending on the size of i
int temp; // the resulting digit will be kept by this temp variable
for (int j=0; j<size; j++){
number=number.concat("0");
}
Integer multi = Integer.valueOf(number); // the variable used for dividing step by step the number we received
while(b){
multi=multi/10;
temp=i/(multi);
li.add(temp);
i=i%(multi);
if(i==0){
b=false;
}
}
for(Integer in: li){
System.out.print(in.intValue()+ " ");
}
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int num=sc.nextInt();
System.out.println("Enter a number (-1 to end):"+num);
int result=0;
int i=0;
while(true)
{
int n=num%10;
if(n==-1){
break;
}
i++;
System.out.println("Digit"+i+" = "+n);
result=result*10+n;
num=num/10;
if(num==0)
{
break;
}
}
}
}

Removing first digit from int, but keeping leading zeros

I need to write code for removing the first digit if an int is more than 3 digits. For example if I have 1055 then the output would be 055. My current code removes the first digit but the problem is it also removes the zeros and outputs 55 instead of 055. How would I got about to fix this? The variable that I'm referring to is the checksum
int checksum = 0;
int l = message.length();
for (int i = 0; i < l; i++) { 3
checksum += message.charAt(i);
}
if (checksum >= 1000) {
checksum = Integer.parseInt(Integer.toString(checksum).substring(1));
}
physicalLayer.sendFrame("(" + message + ":" + checksum + ":.)");
You obviously cannot keep leading zeros in int data type.
So, keep the result in a String copy
int checksum=0;
int l= message.length();
for (int i = 0; i < l; i++) {
checksum+= message.charAt(i);
}
String sChecksum = Integer.toString(checksum);
if(checksum>=1000){
sChecksum= sChecksum.substring(1);
}
physicalLayer.sendFrame("("+message+":"+sChecksum+":.)");
You mention if the it is more than 4 digits then
int number = 1055;
String text_no = Integer.toString(number);
//System.out.println(text_no.substring(1,3));
if(text_no.length() > 4) {
System.out.println(text_no.substring(1));
}
But "1055" has only 4 digit then if condition does not work if you need to check only 4 digit and more that for digits then this will work
int number = 1055;
String text_no = Integer.toString(number);
//System.out.println(text_no.substring(1,3));
if(text_no.length() >= 4) {
System.out.println(text_no.substring(1));
}

Given a number n, list all n-digit numbers such that each number does not have repeating digits

I'm trying to solve the following problem. Given an integer, n, list all n-digits numbers such that each number does not have repeating digits.
For example, if n is 4, then the output is as follows:
0123
0124
0125
...
9875
9876
Total number of 4-digit numbers is 5040
My present approach is by brute-force. I can generate all n-digit numbers, then, using a Set, list all numbers with no repeating digits. However, I'm pretty sure there is a faster, better and more elegant way of doing this.
I'm programming in Java, but I can read source code in C.
Thanks
Mathematically, you have 10 options for the first number, 9 for the second, 8 for the 3rd, and 7 for the 4th. So, 10 * 9 * 8 * 7 = 5040.
Programmatically, you can generate these with some combinations logic. Using a functional approach usually keeps code cleaner; meaning build up a new string recursively as opposed to trying to use a StringBuilder or array to keep modifying your existing string.
Example Code
The following code will generate the permutations, without reusing digits, without any extra set or map/etc.
public class LockerNumberNoRepeats {
public static void main(String[] args) {
System.out.println("Total combinations = " + permutations(4));
}
public static int permutations(int targetLength) {
return permutations("", "0123456789", targetLength);
}
private static int permutations(String c, String r, int targetLength) {
if (c.length() == targetLength) {
System.out.println(c);
return 1;
}
int sum = 0;
for (int i = 0; i < r.length(); ++i) {
sum += permutations(c + r.charAt(i), r.substring(0,i) + r.substring(i + 1), targetLength);
}
return sum;
}
}
Output:
...
9875
9876
Total combinations = 5040
Explanation
Pulling this from a comment by #Rick as it was very well said and helps to clarify the solution.
So to explain what is happening here - it's recursing a function which takes three parameters: a list of digits we've already used (the string we're building - c), a list of digits we haven't used yet (the string r) and the target depth or length. Then when a digit is used, it is added to c and removed from r for subsequent recursive calls, so you don't need to check if it is already used, because you only pass in those which haven't already been used.
it's easy to find a formula. i.e.
if n=1 there are 10 variants.
if n=2 there are 9*10 variants.
if n=3 there are 8*9*10 variants.
if n=4 there are 7*8*9*10 variants.
Note the symmetry here:
0123
0124
...
9875
9876
9876 = 9999 - 123
9875 = 9999 - 124
So for starters you can chop the work in half.
It's possible that you might be able to find a regex which covers scenarios such that if a digit occurs twice in the same string then it matches/fails.
Whether the regex will be faster or not, who knows?
Specifically for four digits you could have nested For loops:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (j != i) {
for (int k = 0; k < 10; k++) {
if ((k != j) && (k != i)) {
for (int m = 0; m < 10; m++) {
if ((m != k) && (m != j) && (m != i)) {
someStringCollection.add((((("" + i) + j) + k) + m));
(etc)
Alternatively, for a more generalised solution, this is a good example of the handy-dandy nature of recursion. E.g. you have a function which takes the list of previous digits, and required depth, and if the number of required digits is less than the depth just have a loop of ten iterations (through each value for the digit you're adding), if the digit doesn't exist in the list already then add it to the list and recurse. If you're at the correct depth just concatenate all the digits in the list and add it to the collection of valid strings you have.
Backtracking method is also a brute-force method.
private static int pickAndSet(byte[] used, int last) {
if (last >= 0) used[last] = 0;
int start = (last < 0) ? 0 : last + 1;
for (int i = start; i < used.length; i++) {
if (used[i] == 0) {
used[i] = 1;
return i;
}
}
return -1;
}
public static int get_series(int n) {
if (n < 1 || n > 10) return 0;
byte[] used = new byte[10];
int[] result = new int[n];
char[] output = new char[n];
int idx = 0;
boolean dirForward = true;
int count = 0;
while (true) {
result[idx] = pickAndSet(used, dirForward ? -1 : result[idx]);
if (result[idx] < 0) { //fail, should rewind.
if (idx == 0) break; //the zero index rewind failed, think all over.
dirForward = false;
idx --;
continue;
} else {//forward.
dirForward = true;
}
idx ++;
if (n == idx) {
for (int k = 0; k < result.length; k++) output[k] = (char)('0' + result[k]);
System.out.println(output);
count ++;
dirForward = false;
idx --;
}
}
return count;
}

How to print very big numbers to the screen

In an interview I had, I was asked to write a program that prints to the screen the numbers 1,2,3,4,5....until 99999999999999.....?(the last number to print is the digit 9 million times)
You are not allowed to use Big-Integer or any other similar object.
The hint I got is to use modulo and work with strings, I tried to think about it but haven't figured it out.
Thanks in advance
You need an array to store the number, and perform operations on the array.
Here's an example
public class BigNumberTest2 {
public static void main(String[] args) {
/*Array with the digits of the number. 0th index stores the most significant digit*/
//int[] num = new int[1000000];
//Can have a million digits, length is 1 + needed to avoid overflow
int[] num = {0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int base = 10;
int step = 1;
String endNum = "100000000000000000000000000000000000000000000000000020";//Can have a million digits
while(true) {
//Increment by step
for(int carry = step, i = num.length - 1; carry != 0 && i >= 0; i--) {
int newDigit = num[i] + carry;
num[i] = newDigit % base;
carry = newDigit / base;
}
//Find the position of most significant digit
int mostSignificantDigitIndex = 0;
while(num[mostSignificantDigitIndex] == 0) {/*No need to check if firstNonZero < num.length, as start num >=0 */
mostSignificantDigitIndex++;
}
StringBuilder strNum = new StringBuilder();
//Concatenate to get actual string
for(int i = mostSignificantDigitIndex; i < num.length; i++) {
strNum.append(num[i]);
}
System.out.println(strNum);
//Check if number current number is greater or equal to endNum
if(strNum.length() > endNum.length() || (strNum.length() == endNum.length() && strNum.toString().compareTo(endNum) >= 0)) {
break;
}
}
}
}
Output
1000000000000000000000000000000000000000000000000000001
1000000000000000000000000000000000000000000000000000002
1000000000000000000000000000000000000000000000000000003
1000000000000000000000000000000000000000000000000000004
1000000000000000000000000000000000000000000000000000005
1000000000000000000000000000000000000000000000000000006
1000000000000000000000000000000000000000000000000000007
1000000000000000000000000000000000000000000000000000008
1000000000000000000000000000000000000000000000000000009
1000000000000000000000000000000000000000000000000000010
1000000000000000000000000000000000000000000000000000011
1000000000000000000000000000000000000000000000000000012
1000000000000000000000000000000000000000000000000000013
1000000000000000000000000000000000000000000000000000014
1000000000000000000000000000000000000000000000000000015
1000000000000000000000000000000000000000000000000000016
1000000000000000000000000000000000000000000000000000017
1000000000000000000000000000000000000000000000000000018
1000000000000000000000000000000000000000000000000000019
1000000000000000000000000000000000000000000000000000020
Something like this:
This is a PHP, but you could transform it to java easy...
Recursion with increasing number through string.
function nextNum($num="", $step=1, $end="999999999999999999") {
$string = "";
$saving = 0;
for($i=strlen($num)-1; $i>=0; $i--) {
$calc = intval(intval($num[$i]) + $saving);
if ($i==(strlen($num)-1)) $calc = $calc + $step;
if (strlen($calc)==2) {
$calc = $calc."";
$saving = intval($calc[0]);
$calc = intval($calc[1]);
}
else {
$calc = intval($calc);
$saving = 0;
}
$string = $calc . $string;
}
if ($saving!=0) $string = $saving.$string;
echo $string." ";
if ($end == $string || strlen($end)<strlen($string)) { return; }
else return nextNum($string, $step, $end);
}
nextNum("0", 1, "999999999999999999");
I didn't test it... but it should work..

Accessing single letters in String / digits in numbers - Java

I have numeric input (11 digits), and I need to perform some operations on each digit (example: multiply 1st by 5, 2nd by 3, etc.). How can I do so in Java? Is there a simple way to access single letter / digit? Is there another way to do it?
If you don't want to convert the number to a string, then there is a simple trick.
digit = number % 10
will give you the right most digit.
number = number / 10
Will remove the right most digit from the number.
So you can run in a loop until the number reaches 0.
while(0 < number)
{
int digit = number % 10;
number = number / 10;
// do here an operation on the digits
}
You can use a for loop to help you count. For example
for(int index = 0; 0 < number; ++index, number /= 10)
{
int digit = number % 10;
// do an operation on the number according to the 'index' variable
}
Here is a similar StackOverFlow question on a similar question
Well there are many ways you can do it like :
int a = 12345;
int b;
while(a>0)
{
b = a%10;
System.out.print(b + " ");
a = a/10;
}
Here it gives you the digits in reverse order like you will get b=5 then b=4....
You can just manipulate them
Other way
int d = 12345;
String str = String.valueOf(d);
for(int i=0;i<str.length();i++)
{
char c = str.charAt(i);
System.out.print(Character.getNumericValue(c) * 10 + " ");
}
Or
char c[] = str.toCharArray();
for(Character ch : c)
{
System.out.print(Character.getNumericValue(ch) * 2 + " ");
}
You can use .charAt() to get a character from a string. Then using Character.getNumericValue() you can convert the character to an integer.
Like this:
String string = "1434347633";
int digit1 = Character.getNumericValue(string.charAt(1));
Convert that number input to String data type so that you can interpret it as a String.
int numbers = 1122334455; // integer won't be able to save this much data,
// just for example ok,
String numberString = numbers.toString();
foreach (char number in numberString) {
// do work on each of the single character in the string.
}
You should work them out, depending on the some condition.
If you want to access the digits by index without converting to a string, you can use these two functions length and digitAt:
public class DigitAt {
public static int length(long v) {
return (int) Math.ceil(Math.log10(v));
}
public static int digitAt(long v, int digit) {
return (int) ((v / (long) Math.pow(10, length(v) - digit - 1)) % 10);
}
public static void main(String[] args) {
System.out.println("Digits: " + length(1234567));
System.out.println(digitAt(1234567, 0));
System.out.println(digitAt(1234567, 1));
System.out.println(digitAt(1234567, 6));
}
}
public String stringAfterOperations(String digits) {
ArrayList<Integer> z = new ArrayList<Integer>();
for(Character c: digits.toCharArray()) {
z.add(Character.getNumericValue(c));
}
//TODO Set your own operations inside this "for"
for(int i=0; i<z.size(); i++){
if(i == 1){
z.set(i, z.get(i)*4);
}
else if(i == 7){
z.set(i, z.get(i)/3);
}
else {
z.set(i, z.get(i)+2);
}
}
String newString = "";
for(Integer i: z){
newString += i;
}
return newString;
}

Categories

Resources