Number BreakingDown - java

So I was asked to do a code that returns the broken down version of the given number. The output should be like this:
Number to break down: 123045011
100000000
20000000
3000000
0
40000
5000
0
10
1
But what my program does is this:
Number to break down: 123045011
100000001
100000002
100000003
100000000
100000004
100000005
100000000
100000001
100000001
This is my code.
import java.util.Scanner;
public class NumberBreakdown {
public static String brokeDownNumber(int num) {
String numberBrokenDown = "";
int numLength = Integer.toString(num).length();
String numAsString = Integer.toString(num);
for(int i = 0; i < numLength; i++) {
// convert Integer to string by using Integer.toString(varToConvert);
// convert char to String by using Character.toString(varToConvert)
int currentNum = Integer.parseInt(Character.toString(numAsString.charAt(i)));
currentNum += Math.pow(10,numLength - 1);
numberBrokenDown += Integer.toString(currentNum) + "\n";
}
return numberBrokenDown;
}
public static void main(String[] args) {
// no need to change this
Scanner reader = new Scanner(System.in);
System.out.print("Number to break down: ");
int number = Integer.parseInt(reader.nextLine());
System.out.println(brokeDownNumber(number));
}
}
What should I change/do?

Change your for loop as below -
for(int i = 0; i < numLength; i++) {
// convert Integer to string by using Integer.toString(varToConvert);
// convert char to String by using Character.toString(varToConvert)
int currentNum = Integer.parseInt(Character.toString(numAsString.charAt(i)));
int currentNum2 = currentNum*(int) Math.pow(10,numLength - i -1);
numberBrokenDown += Integer.toString(currentNum2) + "\n";
}

Only one line code change is needed.
currentNum *= (int)Math.pow(10, numLength - i - 1);
In each iteration, 10's power should decrease. So, numLength - i - 1 is needed.
+= is changed to *= because currentNum should be multiplied by 10th power to get desired result.

public class NumberBreakdown {
public static String brokeDownNumber(int num) {
String numberBrokenDown = "";
String numAsString = Integer.toString(num);
int numLength = numAsString.length();
for(int i = 0; i < numLength; i++) {
// convert Integer to string by using Integer.toString(varToConvert);
// convert char to String by using Character.toString(varToConvert)
int currentNum = num%10;
num = num/10;
if(currentNum ==0) {
System.out.print("0");
}else {
// currentNum += Math.pow(10,numLength - 1);
// numberBrokenDown += Integer.toString(currentNum) + "\n";
System.out.print(currentNum);
for(int j=0;j<i;j++)
System.out.print("0");
}
System.out.println("");
}
return numberBrokenDown;
}
public static void main(String[] args) {
// no need to change this
Scanner reader = new Scanner(System.in);
System.out.print("Number to break down: ");
int number = Integer.parseInt(reader.nextLine());
brokeDownNumber(number);
}
}

Related

Palindrome in java

Here what I tried
sample input is "aabaa"
eg: in if condition val[0] = a[4]
if it is equal i stored it in counter variable if it is half of the length it original string it is palindrome
if it is not it is not a palindrome
I tried with my basic knowledge in java if there is any errors let me know
boolean solution(String inputString) {
int val = inputString.length();
int count = 0;
for (int i = 0; i<inputString.length(); i++) {
if(inputString.charAt(i) == inputString.charAt(val-i)) {
count = count++;
if (count>0) {
return true;
}
}
}
return true;
}
How about
public boolean isPalindrome(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
int length = clean.length();
int forward = 0;
int backward = length - 1;
while (backward > forward) {
char forwardChar = clean.charAt(forward++);
char backwardChar = clean.charAt(backward--);
if (forwardChar != backwardChar)
return false;
}
return true;
}
From here
In your version you compare first element with last, second with second last etc.
last element in this case is inputString.length()-1(so need to use 'inputString.charAt(val-i-1)' . If you iterate till end, then the count should be equal to length of the string.
for(int i = 0; i<inputString.length(); i++){
if(inputString.charAt(i) == inputString.charAt(val-i-1)){
count ++;
}
}
return (count==val); //true when count=val
Or alternatlively iterate till the mid point of the array, then count value is val/2.
for(int i = 0; i<inputString.length()/2; i++){
if(inputString.charAt(i) == inputString.charAt(val-i-1)){
count ++;
}
}
return (count==val/2); //true when count=val/2
There's no constraints in the question so let me throw in a more cheesy solution.
boolean isPalindrome(String in)
final String inl = in.toLowerCase();
return new StringBuilder(inl).reverse().toString().equals(inl);
}
A palindrome is a word, sentence, verse, or even a number that reads the same forward and backward. In this java solution, we’ll see how to figure out whether the number or the string is palindrome in nature or not.
Method - 1
class Main {
public static void main(String[] args) {
String str = "Nitin", revStr = "";
int strLen = str.length();
for (int i = (strLen - 1); i >=0; --i) {
revStr = revStr + str.charAt(i);
}
if (str.toLowerCase().equals(revStr.toLowerCase())) {
System.out.println(str + " is a Palindrome String.");
}
else {
System.out.println(str + " is not a Palindrome String.");
}
Method - 2
class Main {
public static void main(String[] args) {
int n = 3553, revNum = 0, rem;
// store the number to the original number
int orgNum = n;
/* get the reverse of original number
store it in variable */
while (n != 0) {
remainder = n % 10;
revNum = revNum * 10 + rem;
n /= 10;
}
// check if reversed number and original number are equal
if (orgNum == revNum) {
System.out.println(orgNum + " is Palindrome.");
}
else {
System.out.println(orgNum + " is not Palindrome.");
}

How to find a number with no digit occurring more than once (J3 CCC 2013 from 1987 to 2013)

I'm a grade 11 student and have been given the task to complete this question for homework:
Problem J3/S1: From 1987 to 2013
You might be surprised to know that 2013 is the first year since 1987
with distinct digits.
The years 2014, 2015, 2016, 2017, 2018, 2019
each have distinct digits.
2012 does not have distinct digits,
since the digit 2 is repeated.
Given a year, what is the next year with distinct digits?
Input
The input consists of one integer Y (0 ≤ Y ≤ 10000),
representing the starting year.
Output
The output will be the single integer D,
which is the next year after Y with distinct digits.
Sample Input 1
1987
Sample Output 1
2013
Sample Input 2
999
Sample Output 2
1023
I usually answer these types of questions rather quickly but I am stumped when it comes to this one. I have spent several hours and cannot figure it out. I found out How to identify if a number is distinct or not, but I can't figure out how to add on years and check again, I keep getting errors. I would really appreciate someone's help.
Please keep in mind that I am in grade 11 and this is my first year of working with Java, so please do not use advanced coding, and methods because I won't understand. If you can, please answer it in a class and not the main method.
here is what I tried:
import java.util.*;
import java.io.*;
public class Leavemealone
{
public static void main(String[] args) throws IOException
{
BufferedReader objReader = new BufferedReader(new InputStreamReader(System.in));
int ctr = 0;
String inputStr = "";
int input = 0;
int inputCheck = 0;
System.out.println("Enter somthin: ");
input = Integer.parseInt (objReader.readLine ());
while(ctr == 0)
{
inputStr += input;
Scanner sc = new Scanner(inputStr);
int n = sc.nextInt(); // get year
String s = String.valueOf(n);
int[] num = new int[4];
for (int i = 0; i < s.length(); i++)
{
int x = Integer.parseInt(s.substring(i, i + 1)); // integer at this part in the string
num[i] += x;
}
String apple = (num[0] + "" + num[1] + "" + num[2] + "" + num[3]);
if (num[0] != num[1] &&
num[1] != num[2] &&
num[2] != num[3] &&
num[0] != num[2] &&
num[0] != num[3] &&
num[1] != num[3])
{
ctr++;
//distinct
}
else
{
input++;
//not distinct
}
}
}
}
Thanks in advance!
this is the other code I found online, I just don't know how to put it in a class
import java.util.Scanner;
import java.io.*;
public class Thegoodone
{
public static void main(String[] args) throws IOException
{
BufferedReader objReader = new BufferedReader(new InputStreamReader (System.in));
int ctr = 0;
String input = "";
int inputCheck = 0;
while (ctr == 0)
{
System.out.println("Enter somthin: ");
inputCheck = Integer.parseInt (objReader.readLine ());
if (inputCheck > 0 && inputCheck < 10000)
{
input += inputCheck;
ctr += 1;
}
else
{
System.out.println("invalid input ");
}
}
Scanner sc = new Scanner(input);
int n = sc.nextInt(); // get year
n++; // start from the next year
while (!hasDistinctDidgets(n)) //if there is repeating digits
{
n++;// next year
}
System.out.println(n);// prints year
}
public static boolean hasDistinctDidgets(int n)
{
//System.out.println("a" + n);
String s = String.valueOf(n); // converts the year from int to String
int[] numbers = new int[10]; // index position represents number, element value represents occurrence of that number
for (int i = 0; i < s.length(); i++)
{
int x = Integer.parseInt(s.substring(i, i + 1)); // integer at this part in the string
numbers[x]++; //increase occurrence of this integer in the array
}
//check if any digit occurred more than once in the array
for (int i = 0; i < numbers.length; i ++)
{
if (numbers[i] > 1) //digit occurred more than once
{
return false; //not distinct
}
}
return true; // hasn't returned false yet, so the integer has distinct digits
}
}
so this is how I tried to put it in a class:
import java.util.Scanner;
import java.io.*;
public class Danny3
{
public static void main(String[] args) throws IOException
{
BufferedReader objReader = new BufferedReader(new InputStreamReader (System.in));
int ctr = 0;
String input = "";
int inputCheck = 0;
while (ctr == 0)
{
System.out.println("Enter somthin: ");
inputCheck = Integer.parseInt (objReader.readLine ());
if (inputCheck > 0 && inputCheck < 10000)
{
input += inputCheck;
ctr += 1;
}
else
{
System.out.println("invalid input ");
}
}
Scanner sc = new Scanner(input);
// System.out.println(output);
int n = sc.nextInt(); // get year
n++; // start from the next year
DistinctCheck processing = new DistinctCheck(n);
int output = processing.getSum();
System.out.println(output);
}
}
class DistinctCheck
{
//private int year = 0;
private boolean hasDistinctDidgets;
private int b = 0;
DistinctCheck(int temp)
{
hasDistinctDidgets(temp);
}
private void yearAdd(int b)
{
while(!hasDistinctDidgets(b)) //if there is repeating digits
{
b++;// next year
}
}
private boolean hasDistinctDidgets(int year)
{
String s = String.valueOf(year); // converts the year from int to String
int[] numbers = new int[10]; // index position represents number, element value represents occurrence of that number
for (int i = 0; i < s.length(); i++)
{
int x = Integer.parseInt(s.substring(i, i + 1)); // integer at this part in the string
numbers[x]++; //increase occurrence of this integer in the array
}
//check if any digit occurred more than once in the array
for (int i = 0; i < numbers.length; i ++)
{
if (numbers[i] > 1) //digit occurred more than once
{
return false; //not distinct
}
}
return true; // hasn't returned false yet, so the integer has distinct digits
}
int getSum()
{
return b;// prints year
}
}
I would start with a method to determine if a given int consists of distinct digits. You could use a Set<Character> and add each character from the String to the Set. You will get false on a duplicate. Like,
static boolean distinctDigits(int i) {
String s = String.valueOf(i);
Set<Character> set = new HashSet<>();
for (char c : s.toCharArray()) {
if (!set.add(c)) {
return false;
}
}
return true;
}
Then your main just needs to invoke that. Like,
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int v = s.nextInt();
while (v < 10000) {
v++;
if (distinctDigits(v)) {
break;
}
}
System.out.println(v);
}
i figured it out:
import java.util.*;
public class Apple
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int num = input.nextInt();
Distinct findDistinct = new Distinct(num); // objecct
String output = findDistinct.getDistinctYear();
System.out.println(output);
}
} // end of main
class Distinct
{
private int ctr = 0;
private String yearStr = "";
private String distinctYear = "";
private int year = 0;
Distinct(int n)
{
year = n;
makeDistinct();
}
private void makeDistinct()
{
while(ctr == 0)
{
year += 1; // year will keep increasing until it is distinct
yearStr = Integer.toString(year);
if(isDistinct(yearStr) == true) // if the number is distinct
{
distinctYear = yearStr;
ctr++;
}
}
}
private boolean isDistinct(String yearStr)
{
String eachNum[] = yearStr.split(""); // breaks up each number (char) of yearStr
for(int i = 0; i < eachNum.length; i++)
{
for(int j = 0; j < i; j++)
{
if (eachNum[i].equals(eachNum[j])) // not distinct
{
return false;
}
}
}
return true; // is distinct
}
String getDistinctYear()
{
return distinctYear;
}
}

Creating a toString method that returns an array in java

I have been recently asked to write a toString method that returns a number in an array as follows:
after every 3 digits from the right-hand side of the number it should
add a comma , but if the digits of the number were 3 or less it
doesn't add a comma.
But I've encountered a problem: The method always returns the value 0,. How can I adjust the code to return the correct format?
public class BigNum {
int[] num;
final int MAX_DIGITS = 50;
public BigNum() {
this.num = new int[MAX_DIGITS];
this.num[0] = 0;
for(int i=1 ; i<this.num.length ; i++)
this.num[i] = -1;
}
public BigNum(long n) {
int number = (int)n;
this.num = new int[MAX_DIGITS];
for (int i = 0; i < this.num.length; i++) {
num[i] = number % 10;
number /= 10;
}
}
public String toString(){
String toReturn = "";
this.num = new int[MAX_DIGITS];
for(int i=0 ; i<this.num.length ; i++)
if(this.num.length>=1 && this.num.length<=3)
toReturn = num[i] + "";
for(int j=0 ; j<this.num.length ; j+=3)
toReturn = num[j] + "," ;
return toReturn;
}
You could try the below piece of code. Remember to copy the BigNum constructor. There are a following changes made to following code:
Creating the instance array length equal to number of digits in the input and not equal to MAX_DIGITS.
Changed the toString method.
public BigNum(long n) {
int number = (int)n;
int[] tempNum = new int[MAX_DIGITS];
int counter=0;
while(number>0) {
tempNum[counter] = number % 10;
number /= 10;
counter++;
}
this.num = Arrays.copyOfRange(tempNum, 0, counter);
}
public String toString(){
String toReturn = "";
if(this.num.length>=1 && this.num.length<=3) {
for(int i=this.num.length-1 ; i>=0 ; i--) {
toReturn += num[i];
}
}else {
int commaPos = this.num.length%3==0?3:this.num.length%3;
int counter=0;
while(counter<this.num.length) {
if(counter==commaPos) {
toReturn+=",";
commaPos+=3;
}
toReturn+=num[this.num.length-1-counter]
counter++;
}
}
return toReturn;
}
I tested the above using the following code:
public static void main(String[] args) {
BigNum bn = new BigNum(1234567);
System.out.println(bn);
}
Output: 1,234,567

How do I Input comma sign without Number format in java

I wrote this code with out number format class.
My Question Is: Is there any way to make this process shorter without Number Format Class.
String num=JOptionPane.showInputDialog("enter number");
Int len=num.length();
String res="";
if (len==4){
res=num.charAt(0)+","+num.substring(1);
}
else if(len==5){
res=num.substring(0,2)+","+num.substring(2);
}
else if(len==6){
res=num.substring(0,3)+","+num.substring(3);
}
else if(len==7){
res=num.charAt(0)+","+num.substring(1,4)+","+num.substring(4);
}
else if(len==8){
res=num.substring(0,2)+","+num.substring(2,5)+","+num.substring(5);
}
else if(len==9){
res=num.substring(0,3)+","+num.substring(3,6)+","+num.substring(6);
}
else if(len==10){
res=num.charAt(0)+","+num.substring(1,4)+","+num.substring(4,7)+","+num.substring(7);
}
System.out.println(res);
Something like the following:
public static void main(String[] args) {
int myInt = 1234567890;
StringBuilder str = new StringBuilder(String.valueOf(myInt));
int length = str.length();
int count = 0;
for (int i = length; i > 0; i--) {
count++;
if (count % 3 == 0 && count != length) {
str.insert(i - 1, ",");
}
}
System.out.println("Formatted Number: " + str);
}

Getting group of the same numbers numbers

I'm working on a code which will count how many are the groups with the same number.
For example:
11022 = 2 groups with the same number
1100021 = 2 groups with the same number
12123333 = 1 group with the same number
So far I've come up to this code:
package Numbers;
import java.util.*;
public class Numbers{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int strI ;
strI = scan.nextInt();
int[] a = {strI};
System.out.println(sum(a));
System.out.println("length = "+a.length);
}
public static in sum(int[] a){
int sum = 0;
int last = 0;
for (int i = 0; i < a.length - 1; i++){
if(a[i] == a[i + 1] && last != a[i + 1]){
sum++;
}
last = a[i];
}
return sum;
}
}
My problem is that the inputted number will register as 1 index. is it possible to enter a series of number that will go to different indexes?
This is easiest done by converting it to a string so you don't have to deal with place value. After all, you only care about the characters themselves.
public static void main(String[] args){
// Get number n... Assuming n has been set to the int in question
int n = ...; //Fill in with whatever int you want to test
String s = n + "";
char same = ' ';
int consec = 0;
for(int i = 0; i < s.length() - 1; i++){
if(s.charAt(i) == s.charAt(i+1)){
if(same == ' ')
consec++;
same = s.charAt(i);
}
else{
same = ' ';
}
}
System.out.println(consec);
}
First, you can get the count of consecutive digits with something like
public static int sum(int a) {
String strI = String.valueOf(a);
int count = 0;
boolean inRun = false;
for (int i = 1; i < strI.length(); i++) {
if (strI.charAt(i - 1) == strI.charAt(i)) {
if (inRun) {
continue;
}
inRun = true;
count++;
} else {
inRun = false;
}
}
return count;
}
public static void main(String[] args) {
int[] arr = { 11022, 1100021, 12123333 };
for (int val : arr) {
int count = sum(val);
String group = "groups";
if (count == 1) {
group = "group";
}
System.out.printf("%d = %d %s with the same number%n", val, count, group);
}
}
Output is the requested
11022 = 2 groups with the same number
1100021 = 2 groups with the same number
12123333 = 1 group with the same number
As for your second question, you might read Integer into a List - Java arrays are immutable,
List<Integer> al = new ArrayList<>();
Scanner scan = new Scanner(System.in);
while (scan.hasNextInt()) {
al.add(scan.nextInt());
}
Integer[] arr = al.toArray(new Integer[0]);
System.out.println(Arrays.toString(arr));

Categories

Resources