I am facing a problem while trying to create object with long(integer) as parameter for Number class it says "Error: integer number to large." in Bluej.
/**
* A class that represents a number and can report
* properties of the number.
*/
public class Number
{
private long number;
public Number(long number)
{
this.number = number;
}
/**
* Returns the number of times digitToMatch appears
* in this number.
* #param digitToMatch the digit to search for.
* must be at least 0 and at most 9.
* #return number of occurrences of digitToMatch
*/
public int countMatchingDigits(int digitToMatch)
{
// TODO: count and return the number of times the given digit appears in the number
int count = 0;
if(digitToMatch >= 0 && digitToMatch <= 9)
{
long n = 0;
while(number > 0)
{
n = number % 10;
if(n == digitToMatch)
{
count++;
}
number = number / 10;
}
}
// Hint: The last digit is (int)(numbers % 10).
return count;
}
}
Related
I'm trying to write a function that outputs a step by step long division problem given a dividend and a divisor. It's supposed to look like this:
25 r 2
5 | 125
-10
27
-25
2
I can write the bit with the vertical line easily enough, but I can't figure out how to format the top part with the remainder or the subtraction loop. Any help greatly appreciated
Here's my solution to this problem, you might want to implement some error checking to see if the dividend is larger than the divisor. The spacing might not always work, but I tried with a few numbers and it seemed fine:
int divisor = 5;
int dividend = 127;
int answer = dividend / divisor;
// Set a space constant for formatting
int spaces = (int) Math.log10(dividend) + (int) Math.log10(divisor) + 4;
// Print the initial bracket
for(int i = 0; i < spaces - (int) Math.log10(answer); i ++) {
System.out.print(" ");
}
System.out.println(Integer.toString(answer) + " r " + Integer.toString(dividend % divisor));
System.out.println(Integer.toString(divisor) + " | " + Integer.toString(dividend));
// Do a while loop to do the subtraction
int remainder = dividend;
while(remainder != dividend % divisor) {
// Find how much of the start of the remainder can be subtracted by making it into a string
String test = Integer.toString(remainder);
int sub = Integer.valueOf(test.substring(0, 1));
test = test.substring(1);
int exp = (int) Math.log10(remainder);
while(sub < divisor) {
sub = sub * 10 + Integer.valueOf(test.substring(0, 1));
test = test.substring(1);
exp--;
}
int multiple = sub - (sub % divisor);
//Print the subtraction and remainder lines
for(int i = 0; i < spaces - 1 - exp - (int) Math.log10(multiple); i++) {
System.out.print(" ");
}
System.out.println("-" + Integer.valueOf(multiple));
remainder -= multiple * Math.pow(10, exp);
for(int i = 0; i < spaces - (int) Math.log10(remainder); i++) {
System.out.print(" ");
}
System.out.println(Integer.valueOf(remainder));
}
The tricky part was working out how much of the remainder needed to be isolated (for example with 127 and 5, 1 cannot be divided by 5, so I needed to use 12) which I achieved by making the remainder into a String to interpret it one character at a time (this can be done mathematically but it hurt my head when it didn't work on my first try so I gave up).
Sample output for dividend = 12, divisor = 5:
25 r 2
5 | 127
-10
27
-25
2
Populate an object and then call to print format.
LongDivision.java
public class LongDivision {
/**
* The Number.
*/
String number;
/**
* The Divider.
*/
String divider;
/**
* The Result.
*/
String result;
/**
* The Lines.
*/
List<String> lines;
/**
* Instantiates a new Long divider.
*
* #param number the number
* #param divider the divider
* #param result the result
* #param lines the lines
*/
public LongDivision(String number, String divider, String result, List<String> lines) {
this.number = number;
this.divider = divider;
this.result = result;
this.lines = lines;
}
/**
* Gets number.
*
* #return the number
*/
public String getNumber() {
return number;
}
/**
* Sets number.
*
* #param number the number
*/
public void setNumber(String number) {
this.number = number;
}
/**
* Gets divider.
*
* #return the divider
*/
public String getDivider() {
return divider;
}
/**
* Sets divider.
*
* #param divider the divider
*/
public void setDivider(String divider) {
this.divider = divider;
}
/**
* Gets result.
*
* #return the result
*/
public String getResult() {
return result;
}
/**
* Sets result.
*
* #param result the result
*/
public void setResult(String result) {
this.result = result;
}
/**
* Gets lines.
*
* #return the lines
*/
public List<String> getLines() {
return lines;
}
/**
* Sets lines.
*
* #param lines the lines
*/
public void setLines(List<String> lines) {
this.lines = lines;
}
#Override
public String toString() {
return String.format(
"LongDivider (number=%s, divider=%s, result=%s, lines=%s)", this.number, this.divider, this.result, this.lines);
}
/**
* print format.
*
* #return the string
*/
public String printFormat() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(result+"\n");
stringBuilder.append(repeat("__", 2));
stringBuilder.append("\n");
stringBuilder.append(number + "| " + divider);
stringBuilder.append("\n");
lines.stream().forEach(s -> stringBuilder.append(s+"\n"));
return stringBuilder.toString();
}
public static String repeat(String s, int n) {
if(s == null) {
return null;
}
final StringBuilder sb = new StringBuilder(s.length() * n);
for(int i = 0; i < n; i++) {
sb.append(s);
}
return sb.toString();
}
}
Main class
public class LongDividerSolution {
/**
* The entry point of application.
*
* #param args the input arguments
*/
public static void main(String[] args) {
String number = "945";
String divider = "4";
String result = "236 (1)";
String lineSeparator = "_";
int max = Math.max(number.length(), result.length());
// TODO Implement the calculation itself.
List<String> strings = new ArrayList<>();
strings.add("8");
strings.add(LongDivision.repeat(lineSeparator, max));
strings.add("14");
strings.add(" 12");
strings.add(LongDivision.repeat(lineSeparator,max));
strings.add(" 25");
strings.add(" 24");
strings.add(LongDivision.repeat(lineSeparator,max));
strings.add("( 1 )");
LongDivision longDivision = new LongDivision(number, divider, result,strings);
System.out.println(longDivision.printFormat());
}
}
Output:
236 (1)
___
945| 4
8
_____
14
12
_____
25
24
_____
( 1 )
I made this method for an assignment in class. To count the number of '1's appearing in any given number. I would like to expand on this and learn how to take a number and if it is even number adds one to it. If it is an odd number subtract one from it using recursion and return that changed number.
public static int countOnes(int n){
if(n < 0){
return countOnes(n*-1);
}
if(n == 0){
return 0;
}
if(n%10 == 1){
return 1 + countOnes(n/10);
}else
return countOnes(n/10);
}
0 would = 1 27 would = 36 so on. I would appreciate any help that is given.
You quite often find that using private method in a recursive solution makes your code much clearer.
/**
* Twiddles one digit.
*/
private static int twiddleDigit(int n) {
return (n & 1) == 1 ? n - 1 : n + 1;
}
/**
* Adds one to digits that are even, subtracts one from digits that are odd.
*/
public static int twiddleDigits(int n) {
if (n < 10) return twiddleDigit(n);
return twiddleDigits(n / 10) * 10 + twiddleDigit(n % 10);
}
I am trying to validate IMEI numbers using the code below, the user will enter their number on a page and this then runs isValidIMEI using a string that is converted to a long.
Now this does work for almost all IMEI's that I have come across but for a few iPhone 5's they have a leading 0, so 0133xxxxxxxxxx0 for example. When this is casted to a long the leading 0 is lost so it becomes 14 digits and fails, if I turn off the length checker this still won't work as it will be doubling the wrong digits.
Any idea how I can convert to some kind of number format but keep that leading 0?
/**
* Sum digits
*
* #param n
* #return
*/
private static int sumDig(int n)
{
int a = 0;
while (n > 0)
{
a = a + n % 10;
n = n / 10;
}
return a;
}
/**
* Is valid imei
*
* #param n
* #return
*/
public boolean isValidIMEI(long n)
{
// Converting the number into String
// for finding length
String s = Long.toString(n);
int len = s.length();
Log.v("IMEIValidation", s);
if (len != 15) {
Log.v("IMEIValidation", "Length issue");
return false;
}
int sum = 0;
for (int i = len; i >= 1; i--)
{
int d = (int)(n % 10);
// Doubling every alternate digit
if (i % 2 == 0)
d = 2 * d;
// Finding sum of the digits
sum += sumDig(d);
n = n / 10;
}
Log.v("IMEIValidation", String.valueOf(sum));
Log.v("IMEIValidation", String.valueOf(sum % 10));
return (sum % 10 == 0);
}
My homework question is :Removes the last two digits of a positive integer base 10 number that is greater than 99
* #param n
* a positive integer number greater than 99
* #return the integer produced by removing the last two digits of n
my code is:
public static int removeLastTwoDigits(int n) {
int m = 0;
String sn = Integer.toString(m);
if(n>99 ) {
String result = sn.substring(0, sn.length() - 1);
m = Integer.parseInt(result);
}
return m;
}
Can someone help?
public static int removeLastTwoDigits(int n) {
return n / 100;
}
Hello i need to build a recursion that replace the even digits with zero:
for exmaple - the number 1254 will be 1050
the number 332- will be 330
and the number 24 - will be 0
i started working on it but got pretty clueless after a while
public static int replaceEvenDigitsWithZero(int number){
if(number<1)
return number;
if(number%2==0 && number%10!=0){
int temp=number%10;
return(number/10+replaceEvenDigitsWithZero(number-temp));
}
return(replaceEvenDigitsWithZero(number/10));
}
public static void main(String[] args) {
int num1 = 1254;
System.out.println(num1 + " --> " + replaceEvenDigitsWithZero(num1));
int num2 = 332;
System.out.println(num2 + " --> " + replaceEvenDigitsWithZero(num2));
int num3 = 24;
System.out.println(num3 + " --> " + replaceEvenDigitsWithZero(num3));
int num4 = 13;
System.out.println(num4 + " --> " + replaceEvenDigitsWithZero(num4));
}
}
Since your method only looks at the last digit, it should always call itself with input / 10 when input >= 10.
You then take the value returned by the recursion, multiply it by 10 and add the last digit back, if odd.
public static int replaceEvenDigitsWithZero(int number) {
int result = 0;
if (number >= 10)
result = replaceEvenDigitsWithZero(number / 10) * 10;
if (number % 2 != 0)
result += number % 10;
return result;
}
In case you need a 1-liner, here it goes: ;)
public static int replaceEvenDigitsWithZero(int number) {
return (number%2 == 0 ? 0 : number % 10) + (number<10 ? 0 : 10 * replaceEvenDigitsWithZero(number / 10));
}
Well ... designing a recursive algorithm has always the same steps:
Identify the base case, that is the scenario that will terminate the recursive calls.
Reduce the problem to being smaller (towards the base case).
For this requirement the problem can easily be made smaller by dividing by 10. That also easily leads to the base case: A single digit is the base case. So a quick implementation can be:
public static int replaceEvenDigitsWithZero(int number) {
// I added handling of negative numbers ...
if (number < 0) {
return -replaceEvenDigitsWithZero(-number);
}
// base case
if (number < 10) {
return replaceOneDigit(number);
}
// recursion
int lastDigit = number % 10;
int remainder = number / 10;
return replaceEvenDigitsWithZero(remainder) * 10 + replaceOneDigit(lastDigit);
}
public static int replaceOneDigit(int digit) {
return (digit % 2 == 0) ? 0 : digit;
}
I added a helper method for converting even digits to zero.
The output now is:
1254 --> 1050
332 --> 330
24 --> 0
13 --> 13
You need to take track of the current position in your number.
In your current function, you will return only the first digit of your number (because you divide it by 10 everytime the recursion is called).
public static int replaceEvenDigitsWithZero(int number, int position){
// cancel condition:
if(number < 10 * position) {
return number;
}
// edit number:
if (position > 0) {
int currentNumber = number / (10 * position);
} else {
currentNumber = number;
}
if(currentNumber%2==0){ //even?
int multiplyValue = currentNumber % 10; // get rest of division by 10 (== digit in current position)
number = number - (multiplyValue * (10 * position)); // set current position to zero
}
// recursive call:
return replaceEvenDigitsWithZero(number,position+1);
}
Didn't test my code, but I hope you get an idea of how to do it.
Use replaceEvenDigitsWithZero(num1,0) to start.
1 convert to String
2 F(string): take the first number: replace 2,4,6,8 characters by 0
3 concatenate to F(the remaining string)
4 convert to int