Next greatest number - java

I'm trying to find the next greatest number from the user input.If the user gives 23 it shows the output as 32.If there is number greater number then it has to print the same given number.But if the user gives 03 it shows 3 but it has to show 30.Because it takes 03 as octal number.How can i change the code to show the correct output as 30?
public class Main
{
static void swap(char ar[], int i, int j)
{
char temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num = in .nextInt();
char[] chars = ("" + num).toCharArray();
int i;
int n = chars.length;
for (i = n - 1; i > 0; i--)
{
if (chars[i] > chars[i - 1])
break;
}
if (i == 0)
System.out.println(num);
else {
int x = chars[i - 1], min = i;
for (int j = i + 1; j<n; j++)
{
if (chars[j] > x && chars[j]<chars[min])
min = j;
}
swap(chars, i - 1, min);
Arrays.sort(chars, i, n);
for (i = 0; i<n; i++)
System.out.print(chars[i]);
}
}
}

package com.demo;
import java.util.Arrays;
import java.util.Scanner;
public class Demo {
static void swap(char ar[], int i, int j)
{
char temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
//int num = in .nextInt();
char[] chars=null;
String numStr=in.next();
int num= Integer.valueOf(numStr);
if(numStr.startsWith("0")) {
chars= ("0" + num).toCharArray();
}else {
chars= ("" + num).toCharArray();
}
int i;
int n = chars.length;
for (i = n - 1; i > 0; i--)
{
if (chars[i] > chars[i - 1])
break;
}
if (i == 0)
System.out.println(num);
else {
int x = chars[i - 1], min = i;
for (int j = i + 1; j<n; j++)
{
if (chars[j] > x && chars[j]<chars[min])
min = j;
}
swap(chars, i - 1, min);
Arrays.sort(chars, i, n);
for (i = 0; i<n; i++)
System.out.print(chars[i]);
}
}
}

public static int findNextGreatestNumber(int[] arr, int k) {
int delta = Integer.MAX_VALUE;
int res = 0;
for (int a : arr) {
if (a - k > 0 && a - k < delta) {
delta = a - k;
res = a;
}
}
return delta == Integer.MAX_VALUE ? k : res;
}

You are reading the numbers from standard input as integers. Try reading them as strings instead:
Scanner in = new Scanner(System.in);
String num = in.nextLine();
char[] chars = num.toCharArray();

In your main(),take the input as String only, instead of taking it as integer.
String num=in.next();

Related

How can I test credit numbers with hyphens (" -" ) to get it as INVALID . When I tried 4003-6000-0000-0014 i am getting errors

I cant get credit card numbers containing hymens as INVALID such as 4003-6000-0000-0014 must give me INVALID but its giving me errors of string.
public class prog {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in) ;
System.out.println("How many credit card you want to check?");
int numOfCredit = userInput.nextInt() ;
int creditnumbers[] = new int[numOfCredit] ;
for (int i = 0 ; i<numOfCredit ; i++)
{
System.out.println("Enter credit card number "+(i+1)+": ") ;
String creditNumber = userInput.next() ;
validateCreditCardNumber(creditNumber);
}
}
private static void validateCreditCardNumber(String str) { // function to check credit numbers
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++)
{
sum += ints[i];
}
if (sum % 10 == 0)
{
System.out.println("VALID");
}
else
{
System.out.println("INVALID");
}
}
}
I get these errors after running with hymens :
Exception in thread "main" java.lang.NumberFormatException: For input string: "-"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:642)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at testing/testing.prog.validateCreditCardNumber(prog.java:33)
at testing/testing.prog.main(prog.java:22)
you can replace in your string "-" with "" (blank) and then apply this function:
String card = "4003-6000-0000-0014";
Boolean t = check(card.replace("-",""));
public static boolean check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}

Reverse and sum the number occurrence in string - java

I would like to write a function that will be reverse a number and then sum it up.
For example, the input string is
We have 55 guests in room 38
So the expected output should be
83 + 55 = 138
I have face a question is that I can't read the last number
example:
input string is '8 people'
output is 0
Here's the code I've written :
int total = 0;
String num = "";
String a = input.nextLine();
for (int i = a.length() - 1; i > 0; i--) {
if (Character.isDigit(a.charAt(i))) {
num += a.charAt(i);
if (!Character.isDigit(a.charAt(i - 1))) {
total += Integer.valueOf(num);
num = "";
}
}
}
All you really need to do is :
String input = "We have 55 guests in room 38";
int sum = 0;
String[] split = input.split(" "); // split based on space
for (int i = 0; i < split.length; i++) {
if (split[i].matches("[0-9]+")) {
sum = sum + Integer.parseInt(new StringBuffer(split[i]).reverse().toString());
}
}
System.out.println(sum);
Explanation:
Here we use regex to check if the String split contains only
digits.
Now we reverse the String and then parse it to an int before
summing.
Try this and works for any input in the form "We have x guests in room y". For your program however, instead if the for loop > 0 do > -1 I think:
Scanner scan = new Scanner(System.in);
scan.next(); scan.next();
String numberOne = "" + scan.nextInt();
scan.next(); scan.next(); scan.next();
String numberTwo = "" + scan.nextInt();
// String numberOne = "" + scan.nextInt(), numberTwo = "" + scan.nextInt();
String numberOneReversed = "", numberTwoReversed = "";
for(int k = numberOne.length() - 1; k > -1; k--)
numberOneReversed += numberOne.charAt(k);
for(int k = numberTwo.length() - 1; k > -1; k--)
numberTwoReversed += numberTwo.charAt(k);
int sum = Integer.parseInt(numberOneReversed) + Integer.parseInt(numberTwoReversed);
System.out.println("" + numberOneReversed + " + " + numberTwoReversed + " = " + sum);
scan.close();
Note for your program as defined in your question:
for (int i = a.length() - 1; i > -1; i--) {
instead of
for (int i = a.length() - 1; i > 0; i--) {
and
if (i != 0 && !Character.isDigit(a.charAt(i - 1))) {
instead of
for (int i = a.length() - 1; i > 0; i--) {
Will return the sum correctly.
Okay here is what I created using BigIntegers instead of ints:
public static BigInteger nameOfFunctionGoesHere(String input) {
BigInteger total = new BigInteger(new byte[] {0});
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total.add(new BigInteger(new String(flipped)));
i = j;
} else {
i++;
}
}
return total;
}
You can of course use ints as well like this:
public static int nameOfFunctionGoesHere(String input) {
int total = 0;
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total + Integer.parseInt(new String(flipped));
i = j;
} else {
i++;
}
}
return total;
}
With longs too:
public static long nameOfFunctionGoesHere(String input) {
long total = 0;
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total + Long.parseLong(new String(flipped));
i = j;
} else {
i++;
}
}
return total;
}

How to increment integer Array values?

I am designing a problem in which I have to use an int array to add or subtract values. For example instead of changing 100 to 101 by adding 1, I want to do the same thing using the int array. It work like this:
int[] val = new int[3];
val[0] = 1;
val[1] = 0;
val[2] = 0;
val[2] += 1;
so, If I have to get a value of 101, I will add 1 to val[2].
The only problem I have is finding a way to make int array work like how adding and subtracting from an ordinary integer data set works.
Is this possible using a for loop or a while loop?
Any help will be appreciated!
Here's your homework:
public static int[] increment(int[] val) {
for (int i = val.length - 1; i >= 0; i--) {
if (++val[i] < 10)
return val;
val[i] = 0;
}
val = new int[val.length + 1];
val[0] = 1;
return val;
}
Make sure you understand how and why it works before submitting it as your own work.
Solution of this problem is designed by using String
You can refer to this method which will return sum of 2 nos having input in String format.
Input String should contain only digits.
class Demo {
public static String add(String a1, String b1) {
int[] a = String_to_int_Array(a1);
int[] b = String_to_int_Array(b1);
int l = a.length - 1;
int m = b.length - 1;
int sum = 0;
int carry = 0;
int rem = 0;
String temp = "";
if (a.length > b.length) {
while (m >= 0) {
sum = a[l] + b[m] + carry;
carry = sum / 10;
rem = sum % 10;
temp = rem + temp;
m--;
l--;
}
while (l >= 0) {
sum = a[l] + carry;
carry = sum / 10;
rem = sum % 10;
temp = rem + temp;
l--;
}
if (carry > 0) {
temp = carry + temp;
}
} else {
while (l >= 0) {
sum = a[l] + b[m] + carry;
carry = sum / 10;
rem = sum % 10;
temp = rem + temp;
m--;
l--;
}
while (m >= 0) {
sum = b[m] + carry;
carry = sum / 10;
rem = sum % 10;
temp = rem + temp;
m--;
}
if (carry > 0) {
temp = carry + temp;
}
}
return temp;
}
public static int[] String_to_int_Array(String s) {
int arr[] = new int[s.length()], i;
for (i = 0; i < s.length(); i++)
arr[i] = Character.digit(s.charAt(i), 10);
return arr;
}
public static void main(String a[]) {
System.out.println(add("222", "111"));
}
}
Quick & dirty:
static void increment(int[] array){
int i = array.length-1;
do{
array[i]=(array[i]+1)%10;
}while(array[i--]==0 && i>=0);
}
Note the overflow when incementing e.g. {9, 9}. Result is {0, 0} here.
public static void increment() {
int[] acc = {9,9,9,9};
String s="";
for (int i = 0; i < acc.length; i++)
s += (acc[i] + "");
int i = Integer.parseInt(s);
i++;
System.out.println("\n"+i);
String temp = Integer.toString(i);
int[] newGuess = new int[temp.length()];
for (i = 0; i < temp.length(); i++)
{
newGuess[i] = temp.charAt(i) - '0';
}
printNumbers(newGuess);
}
public static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}
If someone is looking for this solution using JavaScript or if you can translate it to java, here's your optimum solution:
function incrementArr(arr) {
let toBeIncrementedFlag = 1, // carry over logic
i = arr.length - 1;
while (toBeIncrementedFlag) {
if (arr[i] === 9) {
arr[i] = 0; // setting the digit as 0 and using carry over
toBeIncrementedFlag = 1;
} else {
toBeIncrementedFlag = 0;
arr[i] += 1;
break; // Breaking loop once no carry over is left
}
if (i === 0) { // handling case of [9,9] [9,9,9] and so on
arr.unshift(1);
break;
}
i--; // going left to right because of carry over
}
return arr;
}

Adding binary numbers

Does anyone know how to add 2 binary numbers, entered as binary, in Java?
For example, 1010 + 10 = 1100.
Use Integer.parseInt(String, int radix).
public static String addBinary(){
// The two input Strings, containing the binary representation of the two values:
String input0 = "1010";
String input1 = "10";
// Use as radix 2 because it's binary
int number0 = Integer.parseInt(input0, 2);
int number1 = Integer.parseInt(input1, 2);
int sum = number0 + number1;
return Integer.toBinaryString(sum); //returns the answer as a binary value;
}
To dive into fundamentals:
public static String binaryAddition(String s1, String s2) {
if (s1 == null || s2 == null) return "";
int first = s1.length() - 1;
int second = s2.length() - 1;
StringBuilder sb = new StringBuilder();
int carry = 0;
while (first >= 0 || second >= 0) {
int sum = carry;
if (first >= 0) {
sum += s1.charAt(first) - '0';
first--;
}
if (second >= 0) {
sum += s2.charAt(second) - '0';
second--;
}
carry = sum >> 1;
sum = sum & 1;
sb.append(sum == 0 ? '0' : '1');
}
if (carry > 0)
sb.append('1');
sb.reverse();
return String.valueOf(sb);
}
Martijn is absolutely correct, to piggyback and complete the answer
Integer.toBinaryString(sum);
would give your output in binary as per the OP question.
You can just put 0b in front of the binary number to specify that it is binary.
For this example, you can simply do:
Integer.toString(0b1010 + 0b10, 2);
This will add the two in binary, and Integer.toString() with 2 as the second parameter converts it back to binary.
The original solution by Martijn will not work for large binary numbers. The below code can be used to overcome that.
public String addBinary(String s1, String s2) {
StringBuilder sb = new StringBuilder();
int i = s1.length() - 1, j = s2.length() -1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0) sum += s2.charAt(j--) - '0';
if (i >= 0) sum += s1.charAt(i--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
public class BinaryArithmetic {
/*-------------------------- add ------------------------------------------------------------*/
static String add(double a, double b) {
System.out.println(a + "first val :" + b);
int a1 = (int) a;
int b1 = (int) b;
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int sum = number0 + number1;
String s3 = Integer.toBinaryString(sum);
return s3;
}
/*-------------------------------multiply-------------------------------------------------------*/
static String multiply(double a, double b) {
System.out.println(a + "first val :" + b);
int a1 = (int) a;
int b1 = (int) b;
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int sum = number0 * number1;
String s3 = Integer.toBinaryString(sum);
return s3;
}
/*----------------------------------------substraction----------------------------------------------*/
static String sub(double a, double b) {
System.out.println(a + "first val :" + b);
int a1 = (int) a;
int b1 = (int) b;
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int sum = number0 - number1;
String s3 = Integer.toBinaryString(sum);
return s3;
}
/*--------------------------------------division------------------------------------------------*/
static String div(double a, double b) {
System.out.println(a + "first val :" + b);
int a1 = (int) a;
int b1 = (int) b;
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int sum = number0 / number1;
String s3 = Integer.toBinaryString(sum);
return s3;
}
}
Another interesting but long approach is to convert each of the two numbers to decimal, adding the decimal numbers and converting the answer obtained back to binary!
Java solution
static String addBinary(String a, String b) {
int lenA = a.length();
int lenB = b.length();
int i = 0;
StringBuilder sb = new StringBuilder();
int rem = Math.abs(lenA-lenB);
while(rem >0){
sb.append('0');
rem--;
}
if(lenA > lenB){
sb.append(b);
b = sb.toString();
}else{
sb.append(a);
a = sb.toString();
}
sb = new StringBuilder();
char carry = '0';
i = a.length();
while(i > 0){
if(a.charAt(i-1) == b.charAt(i-1)){
sb.append(carry);
if(a.charAt(i-1) == '1'){
carry = '1';
}else{
carry = '0';
}
}else{
if(carry == '1'){
sb.append('0');
carry = '1';
}else{
carry = '0';
sb.append('1');
}
}
i--;
}
if(carry == '1'){
sb.append(carry);
}
sb.reverse();
return sb.toString();
}
public String addBinary(String a, String b) {
int carry = 0;
StringBuilder sb = new StringBuilder();
for(int i = a.length() - 1, j = b.length() - 1;i >= 0 || j >= 0;i--,j--){
int sum = carry + (i >= 0 ? a.charAt(i) - '0':0) + (j >= 0 ? b.charAt(j) - '0' : 0);
sb.append(sum%2);
carry =sum / 2;
}
if(carry > 0) sb.append(carry);
sb.reverse();
return sb.toString();
}
I've actually managed to find a solution to this question without using the stringbuilder() function. Check this out:
public void BinaryAddition(String s1,String s2)
{
int l1=s1.length();int c1=l1;
int l2=s2.length();int c2=l2;
int max=(int)Math.max(l1,l2);
int arr1[]=new int[max];
int arr2[]=new int[max];
int sum[]=new int[max+1];
for(int i=(arr1.length-1);i>=(max-l1);i--)
{
arr1[i]=(int)(s1.charAt(c1-1)-48);
c1--;
}
for(int i=(arr2.length-1);i>=(max-l2);i--)
{
arr2[i]=(int)(s2.charAt(c2-1)-48);
c2--;
}
for(int i=(sum.length-1);i>=1;i--)
{
sum[i]+=arr1[i-1]+arr2[i-1];
if(sum[i]==2)
{
sum[i]=0;
sum[i-1]=1;
}
else if(sum[i]==3)
{
sum[i]=1;
sum[i-1]=1;
}
}
int c=0;
for(int i=0;i<sum.length;i++)
{
System.out.print(sum[i]);
}
}
The idea is same as discussed in few of the answers, but this one is a much shorter and easier to understand solution (steps are commented).
// Handles numbers which are way bigger.
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1;
int j = b.length() -1;
int carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0) { sum += b.charAt(j--) - '0' };
if (i >= 0) { sum += a.charAt(i--) - '0' };
// Added number can be only 0 or 1
sb.append(sum % 2);
// Get the carry.
carry = sum / 2;
}
if (carry != 0) { sb.append(carry); }
// First reverse and then return.
return sb.reverse().toString();
}
i tried to make it simple this was sth i had to deal with with my cryptography prj its not efficient but i hope it
public String binarysum(String a, String b){
int carry=0;
int maxim;
int minim;
maxim=Math.max(a.length(),b.length());
minim=Math.min(a.length(),b.length());
char smin[]=new char[minim];
char smax[]=new char[maxim];
if(a.length()==minim){
for(int i=0;i<smin.length;i++){
smin[i]=a.charAt(i);
}
for(int i=0;i<smax.length;i++){
smax[i]=b.charAt(i);
}
}
else{
for(int i=0;i<smin.length;i++){
smin[i]=b.charAt(i);
}
for(int i=0;i<smax.length;i++){
smax[i]=a.charAt(i);
}
}
char[]sum=new char[maxim];
char[] st=new char[maxim];
for(int i=0;i<st.length;i++){
st[i]='0';
}
int k=st.length-1;
for(int i=smin.length-1;i>-1;i--){
st[k]=smin[i];
k--;
}
// *************************** sum begins here
for(int i=maxim-1;i>-1;i--){
char x= smax[i];
char y= st[i];
if(x==y && x=='0'){
if(carry==0)
sum[i]='0';
else if(carry==1){
sum[i]='1';
carry=0;
}
}
else if(x==y && x=='1'){
if(carry==0){
sum[i]='0';
carry=1;
}
else if(carry==1){
sum[i]='1';
carry=1;
}
}
else if(x!=y){
if(carry==0){
sum[i]='1';
}
else if(carry==1){
sum[i]='0';
carry=1;
}
} }
String s=new String(sum);
return s;
}
class Sum{
public int number;
public int carry;
Sum(int number, int carry){
this.number = number;
this.carry = carry;
}
}
public String addBinary(String a, String b) {
int lengthOfA = a.length();
int lengthOfB = b.length();
if(lengthOfA > lengthOfB){
for(int i=0; i<(lengthOfA - lengthOfB); i++){
b="0"+b;
}
}
else{
for(int i=0; i<(lengthOfB - lengthOfA); i++){
a="0"+a;
}
}
String result = "";
Sum s = new Sum(0,0);
for(int i=a.length()-1; i>=0; i--){
s = addNumber(Character.getNumericValue(a.charAt(i)), Character.getNumericValue(b.charAt(i)), s.carry);
result = result + Integer.toString(s.number);
}
if(s.carry == 1) { result += s.carry ;}
return new StringBuilder(result).reverse().toString();
}
Sum addNumber(int number1, int number2, int carry){
Sum sum = new Sum(0,0);
sum.number = number1 ^ number2 ^ carry;
sum.carry = (number1 & number2) | (number2 & carry) | (number1 & carry);
return sum;
}
import java.util.*;
public class BitAddition {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
int[] arr1 = new int[len];
int[] arr2 = new int[len];
int[] sum = new int[len+1];
Arrays.fill(sum, 0);
for(int i=0;i<len;i++){
arr1[i] =sc.nextInt();
}
for(int i=0;i<len;i++){
arr2[i] =sc.nextInt();
}
for(int i=len-1;i>=0;i--){
if(sum[i+1] == 0){
if(arr1[i]!=arr2[i]){
sum[i+1] = 1;
}
else if(arr1[i] ==1 && arr2[i] == 1){
sum[i+1] =0 ;
sum[i] = 1;
}
}
else{
if((arr1[i]!=arr2[i])){
sum[i+1] = 0;
sum[i] = 1;
}
else if(arr1[i] == 1){
sum[i+1] = 1;
sum[i] = 1;
}
}
}
for(int i=0;i<=len;i++){
System.out.print(sum[i]);
}
}
}
One of the simple ways is as:
convert the two strings to char[] array and set carry=0.
set the smallest array length in for loop
start for loop from the last index and decrement it
check 4 conditions(0+0=0, 0+1=1, 1+0=1, 1+1=10(carry=1)) for binary addition for each element in both the arrays and reset the carry accordingly.
append the addition in stringbuffer
append rest of the elements from max size array to stringbuffer but check consider carry while appending
print stringbuffer in reverse order for the answer.
//The java code is as
static String binaryAdd(String a, String b){
int len = 0;
int size = 0;
char[] c1 = a.toCharArray();
char[] c2 = b.toCharArray();
char[] max;
if(c1.length > c2.length){
len = c2.length;
size = c1.length;
max = c1;
}
else
{
len = c1.length;
size = c2.length;
max = c2;
}
StringBuilder sb = new StringBuilder();
int carry = 0;
int p = c1.length - 1;
int q = c2.length - 1;
for(int i=len-1; i>=0; i--){
if(c1[p] == '0' && c2[q] == '0'){
if(carry == 0){
sb.append(0);
carry = 0;
}
else{
sb.append(1);
carry = 0;
}
}
if((c1[p] == '0' && c2[q] == '1') || (c1[p] == '1' && c2[q] == '0')){
if(carry == 0){
sb.append(1);
carry = 0;
}
else{
sb.append(0);
carry = 1;
}
}
if((c1[p] == '1' && c2[q] == '1')){
if(carry == 0){
sb.append(0);
carry = 1;
}
else{
sb.append(1);
carry = 1;
}
}
p--;
q--;
}
for(int j = size-len-1; j>=0; j--){
if(max[j] == '0'){
if(carry == 0){
sb.append(0);
carry = 0;
}
else{
sb.append(1);
carry = 0;
}
}
if(max[j] == '1'){
if(carry == 0){
sb.append(1);
carry = 0;
}
else{
sb.append(0);
carry = 1;
}
}
}
if(carry == 1)
sb.append(1);
return sb.reverse().toString();
}
import java.io.;
import java.util.;
public class adtbin {
static Scanner sc=new Scanner(System.in);
public void fun(int n1) {
int i=0;
int sum[]=new int[20];
while(n1>0) {
sum[i]=n1%2; n1=n1/2; i++;
}
for(int a=i-1;a>=0;a--) {
System.out.print(sum[a]);
}
}
public static void main() {
int m,n,add;
adtbin ob=new adtbin();
System.out.println("enter the value of m and n");
m=sc.nextInt();
n=sc.nextInt();
add=m+n;
ob.fun(add);
}
}
you can write your own One.
long a =100011111111L;
long b =1000001111L;
int carry = 0 ;
long result = 0;
long multiplicity = 1;
while(a!=0 || b!=0 || carry ==1){
if(a%10==1){
if(b%10==1){
result+= (carry*multiplicity);
carry = 1;
}else if(carry == 1){
carry = 1;
}else{
result += multiplicity;
}
}else if (b%10 == 1){
if(carry == 1){
carry = 1;
}else {
result += multiplicity;
}
}else {
result += (carry*multiplicity);
carry = 0;
}
a/=10;
b/=10;
multiplicity *= 10;
}
System.out.print(result);
it works just by numbers , no need string , no need SubString and ...
package Assignment19thDec;
import java.util.Scanner;
public class addTwoBinaryNumbers {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.println("Enter 1st Binary Number");
int number1=sc.nextInt();
int reminder1=0;
int number2=sc.nextInt();
int reminder2=0;
int carry=0;
double sumResult=0 ;int add = 0
;
int n;
int power=0;
while (number1>0 || number2>0) {
/*System.out.println(number1 + " " +number2);*/
reminder1=number1%10;
number1=number1/10;
reminder2=number2%10;
number2=number2/10;
/*System.out.println(reminder1 +" "+ reminder2);*/
if(reminder1>1 || reminder2>1 ) {
System.out.println("not a binary number");
System.exit(0);
}
n=reminder1+reminder2+carry;
switch(n) {
case 0:
add=0; carry=0;
break;
case 1: add=1; carry=0;
break;
case 2: add=0; carry=1;
break;
case 3: add=1;carry=1;
break;
default: System.out.println("not a binary number ");
}
sumResult=add*(Math.pow(10, power))+sumResult;
power++;
}
sumResult=carry*(Math.pow(10, power))+sumResult;
System.out.println("\n"+(int)sumResult);
}
}
Try this, tested with binary and decimal and its self explanatory
public String add(String s1, String s2, int radix){
int s1Length = s1.length();
int s2Length = s2.length();
int reminder = 0;
int carry = 0;
StringBuilder result = new StringBuilder();
int i = s1Length -1;
int j = s2Length -1;
while (i >=0 && j>=0) {
int operand1 = Integer.valueOf(s1.charAt(i)+"");
int operand2 = Integer.valueOf(s2.charAt(j)+"");
reminder = (operand1+operand2+carry) % radix;
carry = (operand1+operand2+carry) / radix;
result.append(reminder);
i--;j--;
}
while(i>=0){
int operand1 = Integer.valueOf(s1.charAt(i)+"");
reminder = (operand1+carry) % radix;
carry = (operand1+carry) / radix;
result.append(reminder);
i--;
}
while(j>=0){
int operand1 = Integer.valueOf(s2.charAt(j)+"");
reminder = (operand1+carry) % radix;
carry = (operand1+carry) / radix;
result.append(reminder);
j--;
}
return result.reverse().toString();
}
}
static int addBinaryNumbers(String a, String b) {
int firstToDecimal = 0;
int secondToDecimal = 0;
for (int i = a.length() - 1, count = 0; i >= 0; i--, count++) {
firstToDecimal += (Math.pow(2, count) * Integer.parseInt(String.valueOf(a.toCharArray()[i])));
}
for (int i = b.length() - 1, count = 0; i >= 0; i--, count++) {
secondToDecimal += (Math.pow(2, count) * Integer.parseInt(String.valueOf(b.toCharArray()[i])));
}
return firstToDecimal + secondToDecimal;
}
public static void main(String[] args) {
System.out.println(addBinaryNumbers("101", "110"));
}
here's a python version that
def binAdd(s1, s2):
if not s1 or not s2:
return ''
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) + int(s2[i])
if s == 2: #1+1
if carry == 0:
carry = 1
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
elif s == 1: # 1+0
if carry == 1:
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
else: # 0+0
if carry == 1:
result = "%s%s" % (result, '1')
carry = 0
else:
result = "%s%s" % (result, '0')
i = i - 1;
if carry>0:
result = "%s%s" % (result, '1')
return result[::-1]
import java.util.Scanner;
{
public static void main(String[] args)
{
String b1,b2;
Scanner sc= new Scanner(System.in);
System.out.println("Enter 1st binary no. : ") ;
b1=sc.next();
System.out.println("Enter 2nd binary no. : ") ;
b2=sc.next();
int num1=Integer.parseInt(b1,2);
int num2=Integer.parseInt(b2,2);
int sum=num1+num2;
System.out.println("Additon is : "+Integer.toBinaryString(sum));
}
}

how to factor a number java

I need to factorize a number like 24 to 1,2,2,2,3. My method for that:
static int[] factorsOf (int val) {
int index = 0;
int []numArray = new int[index];
System.out.println("\nThe factors of " + val + " are:");
for(int i=1; i <= val/2; i++)
{
if(val % i == 0)
{
numArray1 [index] = i;
index++;
}
}
return numArray;
}
however, it is not working. Can anyone help me for that?
You have a few errors, you cannot create int array without size. I used array list instead.
static Integer[] factorsOf(int val) {
List<Integer> numArray = new ArrayList<Integer>();
System.out.println("\nThe factors of " + val + " are:");
for (int i = 2; i <= Math.ceil(Math.sqrt(val)); i++) {
if (val % i == 0) {
numArray.add(i);
val /= i;
System.out.print(i + ", ");
}
}
numArray.add(val);
System.out.print(val);
return numArray.toArray(new Integer[numArray.size()]);
}
Full program using int[] according to your request.
public class Test2 {
public static void main(String[] args) {
int val = 5;
int [] result = factorsOf(val);
System.out.println("\nThe factors of " + val + " are:");
for(int i = 0; i < result.length && result[i] != 0; i ++){
System.out.println(result[i] + " ");
}
}
static int[] factorsOf(int val) {
int limit = (int) Math.ceil(Math.sqrt(val));
int [] numArray = new int[limit];
int index = 0;
for (int i = 1; i <= limit; i++) {
if (val % i == 0) {
numArray[index++] = i;
val /= i;
}
}
numArray[index] = val;
return numArray;
}
}
public int[] primeFactors(int num)
{
ArrayList<Integer> factors = new ArrayList<Integer>();
factors.add(1);
for (int a = 2; num>1; )
if (num%a==0)
{
factors.add(a);
num/=a;
}
else
a++;
int[] out = new int[factors.size()];
for (int a = 0; a < out.length; a++)
out[a] = factors.get(a);
return out;
}
Are you looking a more faster way?:
static int[] getFactors(int value) {
int[] a = new int[31]; // 2^31
int i = 0, j;
int num = value;
while (num % 2 == 0) {
a[i++] = 2;
num /= 2;
}
j = 3;
while (j <= Math.sqrt(num) + 1) {
if (num % j == 0) {
a[i++] = j;
num /= j;
} else {
j += 2;
}
}
if (num > 1) {
a[i++] = num;
}
int[] b = Arrays.copyOf(a, i);
return b;
}
Most of the approaches suggested here have 0(n) time complexity. This can be easily resolved using binary search approach with 0(log n) time complexity.
What do you basically are looking for is called Prime Factors (although 1 is not considered among prime factors).
//finding any occurrence of the no by binary search
static int[] primeFactors(int number) {
List<Integer> al = new ArrayList<Integer>();
//since you wanted 1 in the res adn every no will be divided by 1;
al.add(1);
for(int i = 2; i< number; i++) {
while(number%i == 0) {
al.add(i);
number = number/i;
}
}
if(number >2)
al.add(number);
int[] res = new int[al.size()];
for(int i=0; i<al.size(); i++)
res[i] = al.get(i);
return res;
}
Say input is 24, we keep dividing the input by 2 till all multiples of 2 are gone, the increase i to 3
Here is a link to the working code: http://tpcg.io/AWH2TJ
A Working example
public class Main
{
public static void main(String[] args)
{
System.out.println(factorsOf(24));
}
static List<Integer> factorsOf (int val) {
List<Integer> factors = new ArrayList<Integer>();
for(int i=1; i <= val/2; i++)
{
if(val % i == 0)
{
factors.add(i);
}
}
return factors;
}
}
Rework an algorithm for working with big numbers using BigInteger class. Try this:
import java.math.BigInteger;
class NumbersFactorization {
public void printPrimeNumbers(String bigNumber) {
BigInteger number = new BigInteger(bigNumber);
for (BigInteger i = BigInteger.TWO; i.compareTo(number) <= 0; i = i.add(BigInteger.ONE)) {
while(number.remainder(i) == BigInteger.ZERO) {
System.out.print(i + " ");
number = number.divide(i);
}
}
if (number.compareTo(BigInteger.TWO) > 0) System.out.println(number);
}
}
You just missed one step in if. Following code would be correct:
System.out.println("\nThe factors of " + val + " are:");
You can take a square root of val for comparison and start iterator by value 2
if(val % i == 0)
{
numArray1 [index] = i;
val=val/i; //add this
index++;
}
but here you need to check if index is 2,it is prime.

Categories