how to take apart a number and multiply its digits? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
hi I'm using codeblocks and I'm kinda new,
I want to take apart a number and multiply its digits
and if number is > 9 then once again I want to take apart the digits and multiply them,
example: if I have the number 126 then the new number would be 1*2*6 = 12
but 12 is > 9 then once again the new number is 1*2 = 2, 2 is not >9 then get out of the loop
thanks

please try this program:
public class B {
public static void main(String[] args) {
String number = "126";
int c = 1;
for (int j = number.length() ; j >=0; j--) {
int v = j;
for (int i = 0; i < v; i++) {
String s = ""+number.charAt(i);
c = c* Integer.parseInt(s.trim());
}
System.out.println("result is : "+c);
c = 1;
}
}
}

A simple solution in C:
int muldigits(unsigned int n) {
while (n > 9) {
unsigned int m = n;
for (n = 1; m; n *= m % 10, m /= 10);
}
return n;
}

You need to use a function to work out each digit of the number you have inputted and then iterate until a zero is calculated. Something like this would work, and then just return the remainder of the switch statement:
quotient = number / 10;
remainder = number % 10;
switch(remainder)
{
case 1:
return 1
break;
}

You can create a method to find number characters in the string like below:
public static int Match(String pattern, String word) {
int abc = 1;
Matcher m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(word);
while (m.find()) {
abc *= Integer.parseInt(m.group());
System.out.println("val of abc when (m=" + m.group() + ") - " + abc);
}
System.out.println("*************************");
return abc;
}
Then you can check the given String inside your main method until you get the required number:
String word = "126 Florida Beach";
String pattern = "\\d";
int abc = 1;
do {
System.out.println("word at - " + word);
System.out.println("abc at - " + abc);
abc = Match(pattern, word);
word = String.valueOf(abc);
} while (abc > 9);
System.out.println("Required Value - " + abc);

Related

Google Foobar Challenge Level 2 "Hey-I-Already-Did-That" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I need help with solving the second level of Google's Foobar challenge.
Commander Lambda uses an automated algorithm to assign minions randomly to tasks, in order to keep her minions on their toes. But you've noticed a flaw in the algorithm - it eventually loops back on itself, so that instead of assigning new minions as it iterates, it gets stuck in a cycle of values so that the same minions end up doing the same tasks over and over again. You think proving this to Commander Lambda will help you make a case for your next promotion.
You have worked out that the algorithm has the following process:
1) Start with a random minion ID n, which is a nonnegative integer of length k in base b
2) Define x and y as integers of length k. x has the digits of n in descending order, and y has the digits of n in ascending order
3) Define z = x - y. Add leading zeros to z to maintain length k if necessary
4) Assign n = z to get the next minion ID, and go back to step 2
For example, given minion ID n = 1211, k = 4, b = 10, then x = 2111, y = 1112 and z = 2111 - 1112 = 0999. Then the next minion ID will be n = 0999 and the algorithm iterates again: x = 9990, y = 0999 and z = 9990 - 0999 = 8991, and so on.
Depending on the values of n, k (derived from n), and b, at some point the algorithm reaches a cycle, such as by reaching a constant value. For example, starting with n = 210022, k = 6, b = 3, the algorithm will reach the cycle of values [210111, 122221, 102212] and it will stay in this cycle no matter how many times it continues iterating. Starting with n = 1211, the routine will reach the integer 6174, and since 7641 - 1467 is 6174, it will stay as that value no matter how many times it iterates.
Given a minion ID as a string n representing a nonnegative integer of length k in base b, where 2 <= k <= 9 and 2 <= b <= 10, write a function solution(n, b) which returns the length of the ending cycle of the algorithm above starting with n. For instance, in the example above, solution(210022, 3) would return 3, since iterating on 102212 would return to 210111 when done in base 3. If the algorithm reaches a constant, such as 0, then the length is 1.
Test Cases: Solution.solution("1211", 10) returns 1
Solution.solution("210022", 3) returns 3
Here is my code:
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
public static int solution(String n, int b) {
int k = n.length();
String m = n;
ArrayList<String> minionID = new ArrayList<>();
while (!minionID.contains(m)) {
minionID.add(m);
char[] s = m.toCharArray();
Arrays.sort(s);
int y = Integer.parseInt(toString(s));
int x = Integer.parseInt(reverseString(s));
if (b == 10) {
int intM = x - y;
m = Integer.toString(intM);
} else {
int intM10 = ((int) Integer.parseInt(toBase10(x,b))) - ((int) Integer.parseInt(toBase10(y, b)));
m = toBaseN(intM10, b);
}
m = addLeadingZeros(k, m);
}
System.out.println(minionID);
return minionID.size() - minionID.indexOf(m);
}
private static String toBaseN (int intBase10, int b) {
int residual = intBase10;
ArrayList<String> digitsBaseN = new ArrayList<>();
while (residual >= b) {
int r = residual % b;
digitsBaseN.add(Integer.toString(residual));
residual = (residual - r) / b;
}
digitsBaseN.add(Integer.toString(residual));
StringBuilder reverseDigits = new StringBuilder();
for (int i = digitsBaseN.size() -1; i >= 0; i--) {
reverseDigits.append(digitsBaseN.get(i));
}
return reverseDigits.toString();
}
private static String toBase10 (int intBaseN, int b) {
int[] xArr = new int[Integer.toString(intBaseN).length()];
int count = 0;
for (int i = xArr.length - 1; i >= 0; i--) {
xArr[count] = Integer.toString(intBaseN).charAt(i) - '0';
count++;
}
int yBase10 = 0;
for(int i = 0; i < xArr.length; i++) {
yBase10 += xArr[i] * (Math.pow(b, i));
}
return Integer.toString(yBase10);
}
public static String toString(char[] arr) {
StringBuilder newString = new StringBuilder();
for (char c : arr) {
newString.append(c);
}
if (newString.toString().contains("-")) {
newString.deleteCharAt(0);
}
return newString.toString();
}
public static String reverseString(char[] arr) {
StringBuilder newString = new StringBuilder();
for (int i = arr.length - 1; i >= 0; i--) {
newString.append(arr[i]);
}
if (newString.toString().contains("-")) {
newString.deleteCharAt(newString.length()-1);
}
return newString.toString();
}
public static String addLeadingZeros(int k, String z) {
if (k > z.length()) {
String zeros = "";
for (int i = 0; i < (k - z.length()); i++) {
zeros += "0";
}
zeros += z;
return zeros;
}
return z;
}
It only works for three out of the ten test cases
def answer(n, b):
k = len(n)
m = n
mini_id = []
while m not in mini_id:
mini_id.append(m)
s = sorted(m)
x_descend = ''.join(s[::-1])
y_ascend = ''.join(s)
if b == 10:
int_m = int(x_descend) - int(y_ascend)
m = str(int_m)
else:
int_m_10 = int(to_base_10(x_descend, b)) - int(to_base_10(y_ascend, b))
m = to_base_n(str(int_m_10), b)
m = (k - len(m)) * '0' + m
return len(mini_id) - mini_id.index(m)

Adding zeroes to front and end of an integer - binary output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I had posted a question yesterday about this program I have been working on but essentially I've programmed an encoder of sorts that takes a string and an integer and then adds to every character within the string the value of the integer and then finally prints the binary of the string assuming 8 bits for every symbol or character. For example ABC with integer(code) 4 should output 01000101 01000110 01000111 (EFG). Now, I've managed to get super close to completing this project but I've run into an issue when converting each character to binary which I assume is due to how I'm actually calculating the binary.
Example: If a binary integer starts with a 0, then obviously I will need to pad the integer with a 0 on the far left. I've managed to do that but there are cases where the integer ends in 0 and I need to do the same thing except on the far right... I'm not sure if I'm making 100% sense but I have posted my code and test result with expected outcome below. As you can see, it converts almost perfectly except the value in the middle (B) adds an extra 2 zeroes instead of just one on the far left and I haven't figured out how to check to add an ending zero. Can someone please help me? How I should go ahead and handle converting to binary(8 bits) from characters?
I also need to figure out how to decode binary into the original message. Example: InputMessage: 01000101 01000110 01000111, InputCode: 4
OriginalMessage: ABC
public class Encoder{
public static void main (String[] args) {
String msg;
int code;
int i;
msg = getMsg();
code = getCode();
getBinaryMsg(getCodedMsg(msg, code));
}
public static String getMsg(){
String msg;
System.out.print("Input message: ");
Scanner input = new Scanner(System.in);
msg = input.nextLine();
return msg;
}
public static int getCode(){
int code=0;
System.out.print("Input Code from 1 - 10: ");
Scanner input = new Scanner(System.in);
return input.nextInt();
}
public static String getCodedMsg(String msg, int code){
int letterOrDigit;
String codedMessage = "";
for(int i = 0; i<= msg.length()-1; i++){
letterOrDigit = msg.charAt(i);
if(Character.isLetter(letterOrDigit)){
letterOrDigit = (char)(msg.charAt(i)+code);
}
if((Character.isLowerCase(msg.charAt(i)) && letterOrDigit > 'z') || (Character.isUpperCase(msg.charAt(i)) && letterOrDigit > 'Z')){
letterOrDigit = (char)(msg.charAt(i) - (26 - code));
}
if(Character.isDigit(letterOrDigit)){
letterOrDigit = (char)(msg.charAt(i)+code);
}
if(Character.isDigit(msg.charAt(i)) && letterOrDigit > '9'){
letterOrDigit = (char)(msg.charAt(i) - (10 - code));
}
codedMessage +=(char)letterOrDigit;
}
return codedMessage;
}
public static void getBinaryMsg(String codedMessage){
char[] strChar = codedMessage.toCharArray();
int character;
int remainder;
int binaryInt;
int revBinInt;
int firstDigit;
String paddedWithZero = "";
String binaryMsg = "";
for(int i = 0; i < strChar.length; i++){
binaryInt = 0;
revBinInt = 0;
firstDigit = 0;
character = strChar[i];
//Calculating 8 binary bits
for(int j = 0; j <= 7; j++){
remainder = character % 2;
binaryInt = binaryInt * 10 + remainder;
character = character / 2;
}
//Reversing the above for loop so that binary is correct
while(binaryInt != 0){
remainder = binaryInt % 10;
revBinInt = revBinInt * 10 + remainder;
binaryInt = binaryInt / 10;
}
firstDigit += revBinInt/(int)(Math.pow(10,(int)Math.log(revBinInt)));
if(firstDigit == 0 && numOfDigits(revBinInt) <= 7){
binaryMsg += String.format("%8s", Integer.toString(revBinInt)).replace(' ', '0') + " ";
}
}
System.out.print(binaryMsg);
}
//Counts the number of digits in case binary number starts or ends in 0
public static int numOfDigits(int number){
int count = 0;
while(number !=0){
number = number/10;
count++;
}
return count;
}
}
Test Result:
Input: ABC, 4
Output: 01000101 00100011 01000111
Expected: 01000101 01000110 01000111
As you say, you were almost done. But the binary encoding wasn't working as expected. Here is my suggestion:
public static void getBinaryMsg(String codedMessage) {
String binary = toBinary(codedMessage);
System.out.println(binary);
}
private static String toBinary(String codedMessage) {
String binary = codedMessage.chars().boxed().map(c -> pad(Integer.toBinaryString(c), 8, '0') + " ").collect(Collectors.joining());
return binary;
}
private static String pad(String s, int n, char c) {
return String.format("%"+n+"s", Integer.parseInt(s)).replace(' ', c);
}
Using Integer.toBinaryString(int i) you don't have to reinvent the wheel. The only thing you have to add is the padding, to get every binary formatted to eight bits. You did it well according to: How to get 0-padded binary representation of an integer in java?
Here's a piece of code that trims zeros on both ends of a binary string:
String s = "00010111110100";
Pattern p = Pattern.compile("(1+[01]*1+)|(1)");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(m.group());
}
It uses a regular expression (1+[01]*1+)|(1).
| in the epression means or, so it says (1+[01]*1+) or (1).
In (1+[01]*1+) 1+ means one or more repetitions of 1 and [01]* means 0 or more repetitions or 1 or 0.
(1) means just 1, to handle the case where your string looks like this: 00010000.
Edit: note that you can actually use (1[01]*1)|(1), since [01]* will handle the case of multiple 1's.

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..

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

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

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