Convert a large 2^63 decimal to binary - java

I need to convert a large decimal to binary how would I go about doing this? Decimal in question is this 3324679375210329505

How about:
String binary = Long.toString(3324679375210329505L, 2);

You may want to go for BigDecimal.
A BigDecimal consists of an arbitrary
precision integer unscaled value and a
32-bit integer scale.The BigDecimal class provides operations for arithmetic, scale
manipulation, rounding, comparison, hashing, and format conversion. The toString() method
provides a canonical representation of a BigDecimal.
new BigDecimal("3324679375210329505").toString(2);

http://www.wikihow.com/Convert-from-Decimal-to-Binary

I would use a Stack! Check if your decimal number is even or odd, if even push a 0 to the stack and if its odd push a 1 to the stack. Then once your decimal number hits 1, you can pop each value from the stack and print each one.
Here is a very inefficient block of code for reference. You will probably have to use long instead of integer.
import java.util.Stack;
public class DecBinConverter {
Stack<Integer> binary;
public DecBinConverter()
{
binary = new Stack<Integer>();
}
public int dec_Bin(int dec)
{
if(dec == 1)
{
System.out.print(1);
return 0;
}
if(dec == 0)
{
System.out.print(0);
return 0;
}
if((dec%2) == 0)
{
binary.push(0);
dec = dec/2;
}
else
{
binary.push(1);
dec = dec/2;
}
while(dec != 1)
{
if((dec%2) == 0)
{
binary.push(0);
dec = dec/2;
}
else
{
binary.push(1);
dec = dec/2;
}
}
if((dec%2) == 0)
{
binary.push(0);
dec = dec/2;
}
else
{
binary.push(1);
dec = dec/2;
}
int x = binary.size();
for(int i = 0; i < x; i++)
{
System.out.print(binary.pop());
}
return 0;
}
}

If you want something fast (over 50% faster than Long.toString(n, 2) and 150-400% faster than BigInteger.toString(2)) that handles negative numbers the same as the built-ins, try the following:
static String toBinary (long n) {
int neg = n < 0 ? 1 : 0;
if(n < 0) n = -n;
int pos = 0;
boolean[] a = new boolean[64];
do {
a[pos++] = n % 2 == 1;
} while ((n >>>= 1) != 0);
char[] c = new char[pos + neg];
if(neg > 0) c[0] = '-';
for (int i = 0; i < pos; i++) {
c[pos - i - 1 + neg] = a[i] ? '1' : '0';
}
return new String(c);
}
If you want the actual Two's Compliment binary representation of the long (with leading 1s or 0s):
static String toBinaryTC (long n) {
char[] c = new char[64];
for(int i = 63; i >= 0; i--, n >>>= 1) {
c[i] = n % 2 != 0 ? '1' : '0';
}
return new String(c);
}

A bit pointless, but here is a solution in C:
void to_binary(unsigned long long n)
{
char str[65], *ptr = str + 1;
str[0] = '\n';
do{
*ptr++ = '0' + (n&1);
} while(n >>= 1);
while(ptr > str)
putc(*--ptr, stdout);
}
For the example, it prints out:
10111000100011101000100100011011011111011110101011010110100001
EDIT: And if you don't mind leading zeros....
void to_binary(unsigned long long n)
{
do{ putc('0' + (n>>63), stdout); } while(n <<= 1);
}

Related

Extracting even digits from int

Here is the problem that I am solving.
Write a method evenDigits that accepts an integer parameter n and that
returns the integer formed by removing the odd digits from n. The
following table shows several calls and their expected return values:
Call Valued Returned
evenDigits(8342116); 8426
evenDigits(4109); 40
evenDigits(8); 8
evenDigits(-34512); -42
evenDigits(-163505); -60
evenDigits(3052); 2
evenDigits(7010496); 46
evenDigits(35179); 0
evenDigits(5307); 0
evenDigits(7); 0
If a negative number with even digits other than 0 is passed to the method, the result should also be negative, as shown above when -34512 is passed.
Leading zeros in the result should be ignored and if there are no even digits other than 0 in the number, the method should return 0, as shown in the last three outputs.
I have this so far -
public static int evenDigits(int n) {
    if (n != 0) { 
        int new_x = 0;
int temp = 0;
String subS = "";
    String x_str = Integer.toString(n);
if (x_str.substring(0, 1).equals("-")) {
 temp = Integer.parseInt(x_str.substring(0, 2));
 subS = x_str.substring(2);
} else {
 temp = Integer.parseInt(x_str.substring(0, 1));
 subS = x_str.substring(1);
}
        if (subS.length() != 0) {
             new_x = Integer.parseInt(x_str.substring(1));
        }
        
        if (temp % 2 == 0) {
             return Integer.parseInt((Integer.toString(temp) + evenDigits(new_x)));
        } else {
            return evenDigits(new_x);
        }
    }
return 0;
}
Why do people seem always to want to convert to String to deal with digits? Java has perfectly good arithmetic primitives for handling the job. For example:
public static int evenDigits(int n) {
int rev = 0;
int digitCount = 0;
// handle negative arguments
if (n < 0) return -evenDigits(-n);
// Extract the even digits to variable rev
while (n != 0) {
if (n % 2 == 0) {
rev = rev * 10 + n % 10;
digitCount += 1;
}
n /= 10;
}
// The digits were extracted in reverse order; reverse them again
while (digitCount > 0) {
n = n * 10 + rev % 10;
rev /= 10;
digitCount -= 1;
}
// The result is in n
return n;
}
Although it makes no difference for a simple academic exercise such as this one, handling the job via arithmetic alone can be expected to perform better than anything involving converting to String.
It's often easier to start with a recursive solution and then work you way back to iterative (if you must):
public static int evenDigits(int n) {
if (n < 0) {
return -evenDigits(-n);
} else if (n == 0) {
return 0;
} else if (n % 2 == 1) {
return evenDigits(n / 10);
} else {
return 10 * evenDigits(n / 10) + (n % 10);
}
}
int n = 8342116;
StringBuilder sb = new StringBuilder();
Integer.toString(n).chars()
.filter(x -> x % 2 == 0)
.mapToObj(i -> (char) i)
.forEachOrdered(sb::append);
int result = Integer.valueOf(sb.toString());
System.out.println(result); // 8426
public int evenDigits(int n) {
int r = 0;
boolean neg = false;
String evenDigits = "";
if (n < 0) { neg = true; n = abs(n); }
// keep dividing n until n = 0
while (n > 0) {
r = n % 10;
n = n / 10; // int division
if (r % 2 == 0) { evenDigits = Integer.toString(r) + evenDigits; }
}
int result = Integer.parseInt(evenDigits);
if (neg) { result -= 2 * result; }
return result;
}
This is more or less a pseudo code, but I think you get my idea. I have used this method for the same problem before.
A layman's solution that's based on Strings:
public static int evenDigits(int n) {
StringBuilder evenDigitsBuffer = new StringBuilder();
for (char digitChar : String.valueOf(n).toCharArray()) {
int digit = Character.getNumericValue(digitChar);
if (digit % 2 == 0) {
evenDigitsBuffer.append(digit);
}
}
return evenDigitsBuffer.length() > 0
? Integer.signum(n) * Integer.parseInt(evenDigitsBuffer.toString())
: 0;
}

An 8-bit representation of decimal Numbers in java

I am currently struggling with an exercise that would convert a signed decimal number between -128 and +127 to its 8-bit binary representation in the two’s complement number system.
I am able to get a representation of the positive numbers, however when the code runs for the input to be a negative, it does the computation, but I am unable to get the right Binary repersentation. For example "57" in 8-bit repersentation would be "00111001" and -57 in the same repersentation would be "11000111"
I am pretty sure I have to do an if statement however I can not get it to work. Very lost
System.out.println("Please enter a decimal to modify into it's binary.");
decimalInput = stdIn.nextInt();
if (decimalInput < 0){
decimalInput= Math.abs(decimalInput);
if(i==0){
binary[i]=1;
}else if (i==1){
binary[i] = 0;
}
}
for ( i = binary.length-1; i >= 0; i--){
remain = decimalInput % 2;
binary[i]=remain;
decimalInput = decimalInput / 2;
}
for (i =0; i <8; i++){
System.out.print(binary[i]);
}
That's because you are again computing the binary of a number in the next for loop with decimalInput (post you take absolute value of decimal number and convert that number to binary). You are repeating the same for loop.
You could do something like:
int computeValue = decimalInput;
if (decimalInput < 0){
computeValue= Math.abs(decimalInput);
}
for (...){
negRemain = computeValue% 2;
...
}
EDIT for 2s complement:
if (decimalInput < 0) {
handleNegativeNumbers(binary);
}
private static void onesComplements(int[] binary) {
for (int i = 0; i < binary.length; i++) {// will perform one's complement
if (binary[i] == 0) {
binary[i] = 1;
} else {
binary[i] = 0;
}
}
}
private static void twosComplement(int[] binary) {
int carry = 1;
for (int i = binary.length - 1; i >= 0; i--) {// will perform two's complement by adding one
if (carry == 1) {
if (binary[i] == 0) {
binary[i] = 1;
carry = 0;
break;
} else {
binary[i] = 0;
}
}
}
}
private static void handleNegativeNumbers(int[] binary) {
onesComplements(binary);
twosComplement(binary);
}

how to find maximum number M less than N in which some specific digit is not allowed to exist in Java

Recently I got a interview programming question about how to find maximum number M less than N, and some specific digit is not allowed to exist in M.
For example, N = 123, digit = 2,then it will output: 119
My ideas is to convert N to string first, and then find the first position of digit from left to right to make this digit decreased by 1. Then I set all the remaining digits in N to 9 to make this number maximized. Does some could point out some corner case which I ignored? and is there some good implementation in Java of this problem for reference?
... convert N to string first, and then find the first position of digit from left to right to make this digit decreased by 1.
That seems difficult. How would you "find the position to make a digit decreased"?
Why not go with a more brute-force approach: keep the number as a number, decrease it one by one, convert to string to find if the digit exists, for example:
public int getMaxN(int N, char digit) {
for (int i = N; i > 0; --i) {
if (Integer.toString(i).indexOf(digit) == -1) {
return i;
}
}
throw new NoSuchElementException();
}
#Test
public void testGetMaxN() {
assertEquals(119, getMaxN(123, '2'));
assertEquals(122, getMaxN(123, '3'));
assertEquals(99, getMaxN(123, '1'));
}
#Test(expected = NoSuchElementException.class)
public void testNoSuchElement() {
getMaxN(0, '0');
}
Probably a more intelligent and efficient method exists.
Attempt 3. Still O(n) but due to the special 0 case needing to cascade back up:
static int banDigit(int number, int digit) {
int length = (Integer.toString(number)).length();
int result = 0;
boolean foundDigit = false;
for (int i = length - 1; i >= 0; i--) {
if (!foundDigit) {
int currentDigit = (int) number / ((int) Math.pow(10, i));
number = number % (int) Math.pow(10, i);
if (currentDigit == digit) {
//if nonzero digit banned, we can just decrement and purge 9 or 8 to right
if (digit > 0) {
currentDigit--;
} else {
// we have to subtract one from the previous
result = result - (int) Math.pow(10, i);
//then we have to check if doing that caused a bunch of ones prior
for (int j = i + 1; j < length; j++) {
if ((int) (result % (int) Math.pow(10, j + 1)) / (int) Math.pow(10, j) == 0) {
result = result - (int) Math.pow(10, j);
}
}
}
foundDigit = true;
}
result += currentDigit * Math.pow(10, i);
} else if (digit == 9) {
result += 8 * Math.pow(10, i);
} else {
result += 9 * Math.pow(10, i);
}
}
return result;
}
The trick I used is to find the correct number to subtract from the original number and max out the rest of the number. This is usually just a number with a 1 in the first bad digit place, but it is a bit more tricky if the banned digit it 0 since it can produce more 0's when the subtraction carries over. This happens when there is a string of digits like 1110 with 1's preceding the 0's. My program keeps track of these in this O(n) time solution where n is the number of digits.
import java.math.BigInteger;
import java.util.Arrays;
public class RemoveDigits {
public static BigInteger removeDigits(BigInteger number, int banned) {
char[] digits = number.toString().toCharArray(); // digits of the number
char[] subtractChars = null; // array used to initialize BigInteger to subtract from the bad digit
char maxDigit = banned == 9 ? '8' : '9'; // digit to fill rest of the number with
int badCarryIndex = -1; // if banned == 0 keep track of the carry possibility
int badDigitIndex = -1;
for (int i = 0; i < digits.length; i++) {
if (banned == 0 && digits[i] == '1') { // keep track of first character affected by carry
if (badCarryIndex < 0) {
badCarryIndex = i;
}
} else if (Character.digit(digits[i], 10) == banned) {
badDigitIndex = i;
if (badCarryIndex != 0) { // calculate the real first character affected by carry
badCarryIndex--;
}
subtractChars = badCarryIndex < 0 ? new char[digits.length - badDigitIndex] : new char[digits.length - badCarryIndex - 1];
subtractChars[0] = '1';
break;
} else { // reset if found a good character
badCarryIndex = -1;
}
}
if (badDigitIndex >= 0) {
// fill the rest of the digits with maxDigit
Arrays.fill(digits, badDigitIndex + 1, digits.length, maxDigit);
// build subtractChars
if (badCarryIndex >= 0) {
// banned == 0, have to worry about carry producing 0's
Arrays.fill(subtractChars, 1, badDigitIndex - badCarryIndex, '1');
Arrays.fill(subtractChars, badDigitIndex - badCarryIndex, subtractChars.length, '0');
} else {
Arrays.fill(subtractChars, 1, subtractChars.length, '0');
}
BigInteger maxedNumber = new BigInteger(new String(digits));
BigInteger subtractNumber = new BigInteger(new String(subtractChars));
return maxedNumber.subtract(subtractNumber);
}
return number; // no bad digits in original number
}
public static void main(String[] args) {
System.out.println(removeDigits(new BigInteger("20"), 0));
System.out.println(removeDigits(new BigInteger("210"), 0));
System.out.println(removeDigits(new BigInteger("123"), 0));
System.out.println(removeDigits(new BigInteger("123"), 2));
System.out.println(removeDigits(new BigInteger("1000"), 0));
System.out.println(removeDigits(new BigInteger("1000"), 1));
System.out.println(removeDigits(new BigInteger("1111020"), 0));
System.out.println(removeDigits(new BigInteger("2011020"), 0));
System.out.println(removeDigits(new BigInteger("80000009"), 9));
System.out.println(removeDigits(new BigInteger("80937921"), 9));
}
}
It prints:
19
199
123
119
999
999
999999
999999
80000008
80888888
Edit: fixed corner case pointed out by JoJo.
I think it works, please tell me if you see any case not well handled.
public static void main(String[] args) {
int N = 100211020;
int digit = 0;
int m;
for (m = 9 ; m > 0 && m == digit; m--);
String sres;
String s = N + "";
int length = s.length();
int i = s.indexOf(digit + "");
if (i < 0)
sres = s;
else {
StringBuilder sb = new StringBuilder();
if (digit != 0) {
for (int j=0 ; j<i ; j++) sb.append(s.charAt(j));
sb.append(digit - 1);
for (int j=i + 1 ; j<length ; j++) sb.append(m);
} else {
if (s.charAt(0) != '1')
sb.append(mod10(s.charAt(0) - '0' - 1));
for (int j=1 ; j<length ; j++) sb.append(9);
}
sres = sb.toString();
}
System.out.println(sres);
}
public static int mod10(int n) {
int res = n % 10;
return res < 0 ? res + 10 : res;
}
EDIT :
I finally decided to use strings to handle the case of digit = 0, which was quite complicated with my first approach.

Manually converting a string to an integer in Java

I'm having string consisting of a sequence of digits (e.g. "1234"). How to return the String as an int without using Java's library functions like Integer.parseInt?
public class StringToInteger {
public static void main(String [] args){
int i = myStringToInteger("123");
System.out.println("String decoded to number " + i);
}
public int myStringToInteger(String str){
/* ... */
}
}
And what is wrong with this?
int i = Integer.parseInt(str);
EDIT :
If you really need to do the conversion by hand, try this:
public static int myStringToInteger(String str) {
int answer = 0, factor = 1;
for (int i = str.length()-1; i >= 0; i--) {
answer += (str.charAt(i) - '0') * factor;
factor *= 10;
}
return answer;
}
The above will work fine for positive integers, if the number is negative you'll have to do a little checking first, but I'll leave that as an exercise for the reader.
If the standard libraries are disallowed, there are many approaches to solving this problem. One way to think about this is as a recursive function:
If n is less than 10, just convert it to the one-character string holding its digit. For example, 3 becomes "3".
If n is greater than 10, then use division and modulus to get the last digit of n and the number formed by excluding the last digit. Recursively get a string for the first digits, then append the appropriate character for the last digit. For example, if n is 137, you'd recursively compute "13" and tack on "7" to get "137".
You will need logic to special-case 0 and negative numbers, but otherwise this can be done fairly simply.
Since I suspect that this may be homework (and know for a fact that at some schools it is), I'll leave the actual conversion as an exercise to the reader. :-)
Hope this helps!
Use long instead of int in this case.
You need to check for overflows.
public static int StringtoNumber(String s) throws Exception{
if (s == null || s.length() == 0)
return 0;
while(s.charAt(0) == ' '){
s = s.substring(1);
}
boolean isNegative = s.charAt(0) == '-';
if (s.charAt(0) == '-' || (s.charAt(0) == '+')){
s = s.substring(1);
}
long result = 0l;
for (int i = 0; i < s.length(); i++){
int value = s.charAt(i) - '0';
if (value >= 0 && value <= 9){
if (!isNegative && 10 * result + value > Integer.MAX_VALUE ){
throw new Exception();
}else if (isNegative && -1 * 10 * result - value < Integer.MIN_VALUE){
throw new Exception();
}
result = 10 * result + value;
}else if (s.charAt(i) != ' '){
return (int)result;
}
}
return isNegative ? -1 * (int)result : (int)result;
}
Alternate approach to the answer already posted here. You can traverse the string from the front and build the number
public static void stringtoint(String s){
boolean isNegative=false;
int number =0;
if (s.charAt(0)=='-') {
isNegative=true;
}else{
number = number* 10 + s.charAt(0)-'0';
}
for (int i = 1; i < s.length(); i++) {
number = number*10 + s.charAt(i)-'0';
}
if(isNegative){
number = 0-number;
}
System.out.println(number);
}
Given the right hint, I think most people with a high school education can solve this own their own. Every one knows 134 = 100x1 + 10x3 + 1x4
The key part most people miss, is that if you do something like this in Java
System.out.println('0'*1);//48
it will pick the decimal representation of character 0 in ascii chart and multiply it by 1.
In ascii table character 0 has a decimal representation of 48. So the above line will print 48. So if you do something like '1'-'0' That is same as 49-48. Since in ascii chart, characters 0-9 are continuous, so you can take any char from 0 to 9 and subtract 0 to get its integer value. Once you have the integer value for a character, then converting the whole string to int is straight forward.
Here is another one solution to the problem
String a = "-12512";
char[] chars = a.toCharArray();
boolean isNegative = (chars[0] == '-');
if (isNegative) {
chars[0] = '0';
}
int multiplier = 1;
int total = 0;
for (int i = chars.length - 1; i >= 0; i--) {
total = total + ((chars[i] - '0') * multiplier);
multiplier = multiplier * 10;
}
if (isNegative) {
total = total * -1;
}
Use this:
static int parseInt(String str) {
char[] ch = str.trim().toCharArray();
int len = ch.length;
int value = 0;
for (int i=0, j=(len-1); i<len; i++,j--) {
int c = ch[i];
if (c < 48 || c > 57) {
throw new NumberFormatException("Not a number: "+str);
}
int n = c - 48;
n *= Math.pow(10, j);
value += n;
}
return value;
}
And by the way, you can handle the special case of negative integers, otherwise it will throw exception NumberFormatException.
You can do like this: from the string, create an array of characters for each element, keep the index saved, and multiply its ASCII value by the power of the actual reverse index. Sum the partial factors and you get it.
There is only a small cast to use Math.pow (since it returns a double), but you can avoid it by creating your own power function.
public static int StringToInt(String str){
int res = 0;
char [] chars = str.toCharArray();
System.out.println(str.length());
for (int i = str.length()-1, j=0; i>=0; i--, j++){
int temp = chars[j]-48;
int power = (int) Math.pow(10, i);
res += temp*power;
System.out.println(res);
}
return res;
}
Using Java 8 you can do the following:
public static int convert(String strNum)
{
int result =strNum.chars().reduce(0, (a, b)->10*a +b-'0');
}
Convert srtNum to char
for each char (represented as 'b') -> 'b' -'0' will give the relative number
sum all in a (initial value is 0)
(each time we perform an opertaion on a char do -> a=a*10
Make use of the fact that Java uses char and int in the same way. Basically, do char - '0' to get the int value of the char.
public class StringToInteger {
public static void main(String[] args) {
int i = myStringToInteger("123");
System.out.println("String decoded to number " + i);
}
public static int myStringToInteger(String str) {
int sum = 0;
char[] array = str.toCharArray();
int j = 0;
for(int i = str.length() - 1 ; i >= 0 ; i--){
sum += Math.pow(10, j)*(array[i]-'0');
j++;
}
return sum;
}
}
public int myStringToInteger(String str) throws NumberFormatException
{
int decimalRadix = 10; //10 is the radix of the decimal system
if (str == null) {
throw new NumberFormatException("null");
}
int finalResult = 0;
boolean isNegative = false;
int index = 0, strLength = str.length();
if (strLength > 0) {
if (str.charAt(0) == '-') {
isNegative = true;
index++;
}
while (index < strLength) {
if((Character.digit(str.charAt(index), decimalRadix)) != -1){
finalResult *= decimalRadix;
finalResult += (str.charAt(index) - '0');
} else throw new NumberFormatException("for input string " + str);
index++;
}
} else {
throw new NumberFormatException("Empty numeric string");
}
if(isNegative){
if(index > 1)
return -finalResult;
else
throw new NumberFormatException("Only got -");
}
return finalResult;
}
Outcome:
1) For the input "34567" the final result would be: 34567
2) For the input "-4567" the final result would be: -4567
3) For the input "-" the final result would be: java.lang.NumberFormatException: Only got -
4) For the input "12ab45" the final result would be: java.lang.NumberFormatException: for input string 12ab45
public static int convertToInt(String input){
char[] ch=input.toCharArray();
int result=0;
for(char c : ch){
result=(result*10)+((int)c-(int)'0');
}
return result;
}
Maybe this way will be a little bit faster:
public static int convertStringToInt(String num) {
int result = 0;
for (char c: num.toCharArray()) {
c -= 48;
if (c <= 9) {
result = (result << 3) + (result << 1) + c;
} else return -1;
}
return result;
}
This is the Complete program with all conditions positive, negative without using library
import java.util.Scanner;
public class StringToInt {
public static void main(String args[]) {
String inputString;
Scanner s = new Scanner(System.in);
inputString = s.nextLine();
if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
System.out.println("error!!!");
} else {
Double result2 = getNumber(inputString);
System.out.println("result = " + result2);
}
}
public static Double getNumber(String number) {
Double result = 0.0;
Double beforeDecimal = 0.0;
Double afterDecimal = 0.0;
Double afterDecimalCount = 0.0;
int signBit = 1;
boolean flag = false;
int count = number.length();
if (number.charAt(0) == '-') {
signBit = -1;
flag = true;
} else if (number.charAt(0) == '+') {
flag = true;
}
for (int i = 0; i < count; i++) {
if (flag && i == 0) {
continue;
}
if (afterDecimalCount == 0.0) {
if (number.charAt(i) - '.' == 0) {
afterDecimalCount++;
} else {
beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
}
} else {
afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
afterDecimalCount = afterDecimalCount * 10;
}
}
if (afterDecimalCount != 0.0) {
afterDecimal = afterDecimal / afterDecimalCount;
result = beforeDecimal + afterDecimal;
} else {
result = beforeDecimal;
}
return result * signBit;
}
}
Works for Positive and Negative String Using TDD
//Solution
public int convert(String string) {
int number = 0;
boolean isNegative = false;
int i = 0;
if (string.charAt(0) == '-') {
isNegative = true;
i++;
}
for (int j = i; j < string.length(); j++) {
int value = string.charAt(j) - '0';
number *= 10;
number += value;
}
if (isNegative) {
number = -number;
}
return number;
}
//Testcases
public class StringtoIntTest {
private StringtoInt stringtoInt;
#Before
public void setUp() throws Exception {
stringtoInt = new StringtoInt();
}
#Test
public void testStringtoInt() {
int excepted = stringtoInt.convert("123456");
assertEquals(123456,excepted);
}
#Test
public void testStringtoIntWithNegative() {
int excepted = stringtoInt.convert("-123456");
assertEquals(-123456,excepted);
}
}
//Take one positive or negative number
String str="-90997865";
//Conver String into Character Array
char arr[]=str.toCharArray();
int no=0,asci=0,res=0;
for(int i=0;i<arr.length;i++)
{
//If First Character == negative then skip iteration and i++
if(arr[i]=='-' && i==0)
{
i++;
}
asci=(int)arr[i]; //Find Ascii value of each Character
no=asci-48; //Now Substract the Ascii value of 0 i.e 48 from asci
res=res*10+no; //Conversion for final number
}
//If first Character is negative then result also negative
if(arr[0]=='-')
{
res=-res;
}
System.out.println(res);
public class ConvertInteger {
public static int convertToInt(String numString){
int answer = 0, factor = 1;
for (int i = numString.length()-1; i >= 0; i--) {
answer += (numString.charAt(i) - '0') *factor;
factor *=10;
}
return answer;
}
public static void main(String[] args) {
System.out.println(convertToInt("789"));
}
}

Fastest algorithm to check if a number is pandigital?

Pandigital number is a number that contains the digits 1..number length.
For example 123, 4312 and 967412385.
I have solved many Project Euler problems, but the Pandigital problems always exceed the one minute rule.
This is my pandigital function:
private boolean isPandigital(int n){
Set<Character> set= new TreeSet<Character>();
String string = n+"";
for (char c:string.toCharArray()){
if (c=='0') return false;
set.add(c);
}
return set.size()==string.length();
}
Create your own function and test it with this method
int pans=0;
for (int i=123456789;i<=123987654;i++){
if (isPandigital(i)){
pans++;
}
}
Using this loop, you should get 720 pandigital numbers. My average time was 500 millisecond.
I'm using Java, but the question is open to any language.
UPDATE
#andras answer has the best time so far, but #Sani Huttunen answer inspired me to add a new algorithm, which gets almost the same time as #andras.
C#, 17ms, if you really want a check.
class Program
{
static bool IsPandigital(int n)
{
int digits = 0; int count = 0; int tmp;
for (; n > 0; n /= 10, ++count)
{
if ((tmp = digits) == (digits |= 1 << (n - ((n / 10) * 10) - 1)))
return false;
}
return digits == (1 << count) - 1;
}
static void Main()
{
int pans = 0;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 123456789; i <= 123987654; i++)
{
if (IsPandigital(i))
{
pans++;
}
}
sw.Stop();
Console.WriteLine("{0}pcs, {1}ms", pans, sw.ElapsedMilliseconds);
Console.ReadKey();
}
}
For a check that is consistent with the Wikipedia definition in base 10:
const int min = 1023456789;
const int expected = 1023;
static bool IsPandigital(int n)
{
if (n >= min)
{
int digits = 0;
for (; n > 0; n /= 10)
{
digits |= 1 << (n - ((n / 10) * 10));
}
return digits == expected;
}
return false;
}
To enumerate numbers in the range you have given, generating permutations would suffice.
The following is not an answer to your question in the strict sense, since it does not implement a check. It uses a generic permutation implementation not optimized for this special case - it still generates the required 720 permutations in 13ms (line breaks might be messed up):
static partial class Permutation
{
/// <summary>
/// Generates permutations.
/// </summary>
/// <typeparam name="T">Type of items to permute.</typeparam>
/// <param name="items">Array of items. Will not be modified.</param>
/// <param name="comparer">Optional comparer to use.
/// If a <paramref name="comparer"/> is supplied,
/// permutations will be ordered according to the
/// <paramref name="comparer"/>
/// </param>
/// <returns>Permutations of input items.</returns>
public static IEnumerable<IEnumerable<T>> Permute<T>(T[] items, IComparer<T> comparer)
{
int length = items.Length;
IntPair[] transform = new IntPair[length];
if (comparer == null)
{
//No comparer. Start with an identity transform.
for (int i = 0; i < length; i++)
{
transform[i] = new IntPair(i, i);
};
}
else
{
//Figure out where we are in the sequence of all permutations
int[] initialorder = new int[length];
for (int i = 0; i < length; i++)
{
initialorder[i] = i;
}
Array.Sort(initialorder, delegate(int x, int y)
{
return comparer.Compare(items[x], items[y]);
});
for (int i = 0; i < length; i++)
{
transform[i] = new IntPair(initialorder[i], i);
}
//Handle duplicates
for (int i = 1; i < length; i++)
{
if (comparer.Compare(
items[transform[i - 1].Second],
items[transform[i].Second]) == 0)
{
transform[i].First = transform[i - 1].First;
}
}
}
yield return ApplyTransform(items, transform);
while (true)
{
//Ref: E. W. Dijkstra, A Discipline of Programming, Prentice-Hall, 1997
//Find the largest partition from the back that is in decreasing (non-icreasing) order
int decreasingpart = length - 2;
for (;decreasingpart >= 0 &&
transform[decreasingpart].First >= transform[decreasingpart + 1].First;
--decreasingpart) ;
//The whole sequence is in decreasing order, finished
if (decreasingpart < 0) yield break;
//Find the smallest element in the decreasing partition that is
//greater than (or equal to) the item in front of the decreasing partition
int greater = length - 1;
for (;greater > decreasingpart &&
transform[decreasingpart].First >= transform[greater].First;
greater--) ;
//Swap the two
Swap(ref transform[decreasingpart], ref transform[greater]);
//Reverse the decreasing partition
Array.Reverse(transform, decreasingpart + 1, length - decreasingpart - 1);
yield return ApplyTransform(items, transform);
}
}
#region Overloads
public static IEnumerable<IEnumerable<T>> Permute<T>(T[] items)
{
return Permute(items, null);
}
public static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<T> items, IComparer<T> comparer)
{
List<T> list = new List<T>(items);
return Permute(list.ToArray(), comparer);
}
public static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<T> items)
{
return Permute(items, null);
}
#endregion Overloads
#region Utility
public static IEnumerable<T> ApplyTransform<T>(
T[] items,
IntPair[] transform)
{
for (int i = 0; i < transform.Length; i++)
{
yield return items[transform[i].Second];
}
}
public static void Swap<T>(ref T x, ref T y)
{
T tmp = x;
x = y;
y = tmp;
}
public struct IntPair
{
public IntPair(int first, int second)
{
this.First = first;
this.Second = second;
}
public int First;
public int Second;
}
#endregion
}
class Program
{
static void Main()
{
int pans = 0;
int[] digits = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Stopwatch sw = new Stopwatch();
sw.Start();
foreach (var p in Permutation.Permute(digits))
{
pans++;
if (pans == 720) break;
}
sw.Stop();
Console.WriteLine("{0}pcs, {1}ms", pans, sw.ElapsedMilliseconds);
Console.ReadKey();
}
}
This is my solution:
static char[][] pandigits = new char[][]{
"1".toCharArray(),
"12".toCharArray(),
"123".toCharArray(),
"1234".toCharArray(),
"12345".toCharArray(),
"123456".toCharArray(),
"1234567".toCharArray(),
"12345678".toCharArray(),
"123456789".toCharArray(),
};
private static boolean isPandigital(int i)
{
char[] c = String.valueOf(i).toCharArray();
Arrays.sort(c);
return Arrays.equals(c, pandigits[c.length-1]);
}
Runs the loop in 0.3 seconds on my (rather slow) system.
Two things you can improve:
You don't need to use a set: you can use a boolean array with 10 elements
Instead of converting to a string, use division and the modulo operation (%) to extract the digits.
Using a bit vector to keep track of which digits have been found appears to be the fastest raw method. There are two ways to improve it:
Check if the number is divisible by 9. This is a necessary condition for being pandigital, so we can exclude 88% of numbers up front.
Use multiplication and shifts instead of divisions, in case your compiler doesn't do that for you.
This gives the following, which runs the test benchmark in about 3ms on my machine. It correctly identifies the 362880 9-digit pan-digital numbers between 100000000 and 999999999.
bool IsPandigital(int n)
{
if (n != 9 * (int)((0x1c71c71dL * n) >> 32))
return false;
int flags = 0;
while (n > 0) {
int q = (int)((0x1999999aL * n) >> 32);
flags |= 1 << (n - q * 10);
n = q;
}
return flags == 0x3fe;
}
My solution involves Sums and Products.
This is in C# and runs in about 180ms on my laptop:
static int[] sums = new int[] {1, 3, 6, 10, 15, 21, 28, 36, 45};
static int[] products = new int[] {1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
static void Main(string[] args)
{
var pans = 0;
for (var i = 123456789; i <= 123987654; i++)
{
var num = i.ToString();
if (Sum(num) == sums[num.Length - 1] && Product(num) == products[num.Length - 1])
pans++;
}
Console.WriteLine(pans);
}
protected static int Sum(string num)
{
int sum = 0;
foreach (char c in num)
sum += (int) (c - '0');
return sum;
}
protected static int Product(string num)
{
int prod = 1;
foreach (char c in num)
prod *= (int)(c - '0');
return prod;
}
Why find when you can make them?
from itertools import *
def generate_pandigital(length):
return (''.join for each in list(permutations('123456789',length)))
def test():
for i in range(10):
print i
generate_pandigital(i)
if __name__=='__main__':
test()
J does this nicely:
isPandigital =: 3 : 0
*./ (' ' -.~ ": 1 + i. # s) e. s =. ": y
)
isPandigital"0 (123456789 + i. 1 + 123987654 - 123456789)
But slowly. I will revise. For now, clocking at 4.8 seconds.
EDIT:
If it's just between the two set numbers, 123456789 and 123987654, then this expression:
*./"1 (1+i.9) e."1 (9#10) #: (123456789 + i. 1 + 123987654 - 123456789)
Runs in 0.23 seconds. It's about as fast, brute-force style, as it gets in J.
TheMachineCharmer is right. At least for some the problems, it's better to iterate over all the pandigitals, checking each one to see if it fits the criteria of the problem. However, I think their code is not quite right.
I'm not sure which is better SO etiquette in this case: Posting a new answer or editing theirs. In any case, here is the modified Python code which I believe to be correct, although it doesn't generate 0-to-n pandigitals.
from itertools import *
def generate_pandigital(length):
'Generate all 1-to-length pandigitals'
return (''.join(each) for each in list(permutations('123456789'[:length])))
def test():
for i in range(10):
print 'Generating all %d-digit pandigitals' % i
for (n,p) in enumerate(generate_pandigital(i)):
print n,p
if __name__=='__main__':
test()
You could add:
if (set.add(c)==false) return false;
This would short circuit a lot of your computations, since it'll return false as soon as a duplicate was found, since add() returns false in this case.
bool IsPandigital (unsigned long n) {
if (n <= 987654321) {
hash_map<int, int> m;
unsigned long count = (unsigned long)(log((double)n)/log(10.0))+1;
while (n) {
++m[n%10];
n /= 10;
}
while (m[count]==1 && --count);
return !count;
}
return false;
}
bool IsPandigital2 (unsigned long d) {
// Avoid integer overflow below if this function is passed a very long number
if (d <= 987654321) {
unsigned long sum = 0;
unsigned long prod = 1;
unsigned long n = d;
unsigned long max = (log((double)n)/log(10.0))+1;
unsigned long max_sum = max*(max+1)/2;
unsigned long max_prod = 1;
while (n) {
sum += n % 10;
prod *= (n%10);
max_prod *= max;
--max;
n /= 10;
}
return (sum == max_sum) && (prod == max_prod);
}
I have a solution for generating Pandigital numbers using StringBuffers in Java. On my laptop, my code takes a total of 5ms to run. Of this only 1ms is required for generating the permutations using StringBuffers; the remaining 4ms are required for converting this StringBuffer to an int[].
#medopal: Can you check the time this code takes on your system?
public class GenPandigits
{
/**
* The prefix that must be appended to every number, like 123.
*/
int prefix;
/**
* Length in characters of the prefix.
*/
int plen;
/**
* The digit from which to start the permutations
*/
String beg;
/**
* The length of the required Pandigital numbers.
*/
int len;
/**
* #param prefix If there is no prefix then this must be null
* #param beg If there is no prefix then this must be "1"
* #param len Length of the required numbers (excluding the prefix)
*/
public GenPandigits(String prefix, String beg, int len)
{
if (prefix == null)
{
this.prefix = 0;
this.plen = 0;
}
else
{
this.prefix = Integer.parseInt(prefix);
this.plen = prefix.length();
}
this.beg = beg;
this.len = len;
}
public StringBuffer genPermsBet()
{
StringBuffer b = new StringBuffer(beg);
for(int k=2;k<=len;k++)
{
StringBuffer rs = new StringBuffer();
int l = b.length();
int s = l/(k-1);
String is = String.valueOf(k+plen);
for(int j=0;j<k;j++)
{
rs.append(b);
for(int i=0;i<s;i++)
{
rs.insert((l+s)*j+i*k+j, is);
}
}
b = rs;
}
return b;
}
public int[] getPandigits(String buffer)
{
int[] pd = new int[buffer.length()/len];
int c= prefix;
for(int i=0;i<len;i++)
c =c *10;
for(int i=0;i<pd.length;i++)
pd[i] = Integer.parseInt(buffer.substring(i*len, (i+1)*len))+c;
return pd;
}
public static void main(String[] args)
{
GenPandigits gp = new GenPandigits("123", "4", 6);
//GenPandigits gp = new GenPandigits(null, "1", 6);
long beg = System.currentTimeMillis();
StringBuffer pansstr = gp.genPermsBet();
long end = System.currentTimeMillis();
System.out.println("Time = " + (end - beg));
int pd[] = gp.getPandigits(pansstr.toString());
long end1 = System.currentTimeMillis();
System.out.println("Time = " + (end1 - end));
}
}
This code can also be used for generating all Pandigital numbers(excluding zero). Just change the object creation call to
GenPandigits gp = new GenPandigits(null, "1", 9);
This means that there is no prefix, and the permutations must start from "1" and continue till the length of the numbers is 9.
Following are the time measurements for different lengths.
#andras: Can you try and run your code to generate the nine digit Pandigital numbers? What time does it take?
This c# implementation is about 8% faster than #andras over the range 123456789 to 123987654 but it is really difficult to see on my test box as his runs in 14ms and this one runs in 13ms.
static bool IsPandigital(int n)
{
int count = 0;
int digits = 0;
int digit;
int bit;
do
{
digit = n % 10;
if (digit == 0)
{
return false;
}
bit = 1 << digit;
if (digits == (digits |= bit))
{
return false;
}
count++;
n /= 10;
} while (n > 0);
return (1<<count)-1 == digits>>1;
}
If we average the results of 100 runs we can get a decimal point.
public void Test()
{
int pans = 0;
var sw = new Stopwatch();
sw.Start();
for (int count = 0; count < 100; count++)
{
pans = 0;
for (int i = 123456789; i <= 123987654; i++)
{
if (IsPandigital(i))
{
pans++;
}
}
}
sw.Stop();
Console.WriteLine("{0}pcs, {1}ms", pans, sw.ElapsedMilliseconds / 100m);
}
#andras implementation averages 14.4ms and this implementation averages 13.2ms
EDIT:
It seems that mod (%) is expensive in c#. If we replace the use of the mod operator with a hand coded version then this implementation averages 11ms over 100 runs.
private static bool IsPandigital(int n)
{
int count = 0;
int digits = 0;
int digit;
int bit;
do
{
digit = n - ((n / 10) * 10);
if (digit == 0)
{
return false;
}
bit = 1 << digit;
if (digits == (digits |= bit))
{
return false;
}
count++;
n /= 10;
} while (n > 0);
return (1 << count) - 1 == digits >> 1;
}
EDIT: Integrated n/=10 into the digit calculation for a small speed improvement.
private static bool IsPandigital(int n)
{
int count = 0;
int digits = 0;
int digit;
int bit;
do
{
digit = n - ((n /= 10) * 10);
if (digit == 0)
{
return false;
}
bit = 1 << digit;
if (digits == (digits |= bit))
{
return false;
}
count++;
} while (n > 0);
return (1 << count) - 1 == digits >> 1;
}
#include <cstdio>
#include <ctime>
bool isPandigital(long num)
{
int arr [] = {1,2,3,4,5,6,7,8,9}, G, count = 9;
do
{
G = num%10;
if (arr[G-1])
--count;
arr[G-1] = 0;
} while (num/=10);
return (!count);
}
int main()
{
clock_t start(clock());
int pans=0;
for (int i = 123456789;i <= 123987654; ++i)
{
if (isPandigital(i))
++pans;
}
double end((double)(clock() - start));
printf("\n\tFound %d Pandigital numbers in %lf seconds\n\n", pans, end/CLOCKS_PER_SEC);
return 0;
}
Simple implementation. Brute-forced and computes in about 140 ms
In Java
You can always just generate them, and convert the Strings to Integers, which is faster for larger numbers
public static List<String> permutation(String str) {
List<String> permutations = new LinkedList<String>();
permutation("", str, permutations);
return permutations;
}
private static void permutation(String prefix, String str, List<String> permutations) {
int n = str.length();
if (n == 0) {
permutations.add(prefix);
} else {
for (int i = 0; i < n; i++) {
permutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i + 1, n), permutations);
}
}
}
The below code works for testing a numbers pandigitality.
For your test mine ran in around ~50ms
1-9 PanDigital
public static boolean is1To9PanDigit(int i) {
if (i < 1e8) {
return false;
}
BitSet set = new BitSet();
while (i > 0) {
int mod = i % 10;
if (mod == 0 || set.get(mod)) {
return false;
}
set.set(mod);
i /= 10;
}
return true;
}
or more general, 1 to N,
public static boolean is1ToNPanDigit(int i, int n) {
BitSet set = new BitSet();
while (i > 0) {
int mod = i % 10;
if (mod == 0 || mod > n || set.get(mod)) {
return false;
}
set.set(mod);
i /= 10;
}
return set.cardinality() == n;
}
And just for fun, 0 to 9, zero requires extra logic due to a leading zero
public static boolean is0To9PanDigit(long i) {
if (i < 1e6) {
return false;
}
BitSet set = new BitSet();
if (i <= 123456789) { // count for leading zero
set.set(0);
}
while (i > 0) {
int mod = (int) (i % 10);
if (set.get(mod)) {
return false;
}
set.set(mod);
i /= 10;
}
return true;
}
Also for setting iteration bounds:
public static int maxPanDigit(int n) {
StringBuffer sb = new StringBuffer();
for(int i = n; i > 0; i--) {
sb.append(i);
}
return Integer.parseInt(sb.toString());
}
public static int minPanDigit(int n) {
StringBuffer sb = new StringBuffer();
for(int i = 1; i <= n; i++) {
sb.append(i);
}
return Integer.parseInt(sb.toString());
}
You could easily use this code to generate a generic MtoNPanDigital number checker
I decided to use something like this:
def is_pandigital(n, zero_full=True, base=10):
"""Returns True or False if the number n is pandigital.
This function returns True for formal pandigital numbers as well as
n-pandigital
"""
r, l = 0, 0
while n:
l, r, n = l + 1, r + n % base, n / base
t = xrange(zero_full ^ 1, l + (zero_full ^ 1))
return r == sum(t) and l == len(t)
Straight forward way
boolean isPandigital(int num,int length){
for(int i=1;i<=length;i++){
if(!(num+"").contains(i+""))
return false;
}
return true;
}
OR if you are sure that the number is of the right length already
static boolean isPandigital(int num){
for(int i=1;i<=(num+"").length();i++){
if(!(num+"").contains(i+""))
return false;
}
return true;
}
I refactored Andras' answer for Swift:
extension Int {
func isPandigital() -> Bool {
let requiredBitmask = 0b1111111111;
let minimumPandigitalNumber = 1023456789;
if self >= minimumPandigitalNumber {
var resultBitmask = 0b0;
var digits = self;
while digits != 0 {
let lastDigit = digits % 10;
let binaryCodedDigit = 1 << lastDigit;
resultBitmask |= binaryCodedDigit;
// remove last digit
digits /= 10;
}
return resultBitmask == requiredBitmask;
}
return false;
}
}
1023456789.isPandigital(); // true
great answers, my 2 cents
bool IsPandigital(long long number, int n){
int arr[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, amax = 0, amin;
while (number > 0){
int rem = number % 10;
arr[rem]--;
if (arr[rem] < 0)
return false;
number = number / 10;
}
for (int i = 0; i < n; i++){
if (i == 0)
amin = arr[i];
if (arr[i] > amax)
amax = arr[i];
if (arr[i] < amin)
amin = arr[i];
}
if (amax == 0 && amin == 0)
return true;
else
return false;
}

Categories

Resources