Guys I really need your help, is this code correct? sometimes if I run it and change the word IMAHACKER to THANKYOU or anything it would work but when I run it again it wouldn't show the message. I think the problem is with the generated numbers? but how do I fix it. I'd really appreciate it if you help because I can't seem to figure out the mistake!
import java.util.*;
public class R{
private Random rnd= new Random();
//Finds the greatest common divisor of two integers, a and b
//Input: a and b integers
//Output: gcd of a and b, using Euclidean method
public long gcd(long a, long b) {
if (b==0)
return a;
return gcd(b,a%b);
}
//Finds the multiplicative inverse of a modulo m
//Input: a an integer, and modulus m
//Output: i: inverse of a modulo m, such that (a*i mod m)=1
public long find_inverse(long a, long m)
{
for (long i=1; i<m; i++)
{
long test=i*a;
if ((test%m)==1)
return i;
}
return 0;
}
//Generates a random prime number
//Input: None
//Output: A random prime number between 2 and 10000
public int random_prime()
{
boolean found=false;
int p=0;
while (!found)
{
p=rnd.nextInt(10000);
found= isPrime(p);
}
return p;
}
//Check if a number is prime or not
//Input: integer p
//Output: True if p is a prime number
//and False if it is composite
public boolean isPrime(int p)
{
if (p>1){
for (int i=2; i<= Math.sqrt(p); i++)
{
if (p%i==0)
return false;
}
return true;
}
return false;
}
static long t=0;
//Generate Keys method
//Input: None
//Output: n_e_d an array of longs containing:
//n_e_d[0]: the modulus n(which is p*q)
//n_e_d[1]: the exponent d(public key)
//n_e_d[2]: d is inverse of e modulo (p-1)*(q-1) (private key)
public long[] generate_keys()
{
long[] n_e_d= new long[3];
int p = random_prime();
int q = random_prime();
long n = p*q;
long euler = (p-1)*(q-1);
t = euler;
int e = random_prime();
long GCD = gcd (e, euler);
while ( e > euler && e < 1 && GCD != 1 )
e = random_prime();
long d = find_inverse(e, euler);
n_e_d[0] = n;
n_e_d[1] = e;
n_e_d[2] = d;
return n_e_d;
}
//Find (b^n mod m) when we are dealing with big numbers
//Same as algorithm 5 in 4.2 in the book
//Input: b: the base, n: the exponent, and m: the modulus
//All inputs are in decimal representation
//Output: Value of (b^n mod m)
public long modular_exponentiation(long b, long n, long m)
{
long x=1;
long pow=b%m;
//COMPLETE HERE (approx 5 lines)
//Convert n to binary (use method Long.toBinaryString(..))
//Iterate over the length of n
//Change pow and x as necessary
String nBi = Long.toBinaryString(n);
int a = 0;
for(int i=0;i<nBi.length();i++){
a = Character.getNumericValue(nBi.charAt(nBi.length()-(i+1)));
if(a==1)
x=(x*pow)%m;
pow=((long)Math.pow(pow,2))%m;}
return x;
}
//Convert from String_to_int
//Make sure you use two digits for each letter (e.g. 01 instead of 1)
//e.g. Input:KBL, Output: 100111
public long string_to_int(String text)
{
//COMPLETE HERE (approx 6 lines)
long num = 0;
String concat ="";
for (int i=0; i<text.length(); i++)
{
char c = text.charAt(i);
String rep = String.valueOf( c - 65 );
if ( rep.length() < 2 )
rep = "0" + rep;
concat = concat + rep ;
num = Long.parseLong(concat);
}
return num;
}
//Convert from int_to_String
//e.g. Input: 100111, Output:KBL
public String int_to_String(long inttext)
{
String text="";
long num=0;
while(inttext>1){
num= inttext%100;
text = String.valueOf((char)(num+65))+text;
inttext = inttext/100;
}
return text;
/*
String text="";
String i = inttext + "";
for(int j=0;j<i.length();j+=2)
text +=Integer.parseInt(i.charAt(j)+""+i.charAt(j+1))>-1 && Integer.parseInt(i.charAt(j)+""+i.charAt(j+1))<26? String.valueOf((char)((Integer.parseInt(i.charAt(j)+""+i.charAt(j+1)))+65)) : null;
return text;*/
}
public int intoBlocks(String s){
int len=0;
int c=0;
if(s.length()%2==0)
len = s.length()/2;
else
len=(s.length()/2)-1;
// System.out.println(len);
return len;
}
public String[] ArrayinBlocks(String s, int x){
String arr[] = new String[s.length()/x];
int j=0;
for(int i=0;i<s.length();i+=x){
arr[j]=s.substring(i,Math.min(s.length(),(i+x)));
j++;}
return arr;
}
//Encryption method
//Input: plaintext, e and n, where:
//Plaintext is a String of uppercase letters only
//e is the public key
//n is the modulus
//Output: Ciphertext, which is an array of longs, each element
// represents the ciphertext of the ith block
public long[] encrypt(String plaintext, long e, long n)
{long[] ciphertext;
int block=intoBlocks(plaintext);
//System.out.println(block);
int t = block;
if(block%2==0){
t = block/2;
ciphertext=new long[block/2];}
else
ciphertext=new long[block];
long C;
//COMPLETE HERE (approx 10 lines)
//Split text into blocks of appropriate size, get their integer representation,
String arr[] = ArrayinBlocks(plaintext,intoBlocks(plaintext));
// System.out.println(arr[0] + " " + arr[1]);
for(int i=0;i<t;i++)
ciphertext[i] = string_to_int(arr[i]);
System.out.println(ciphertext[0] + " " + ciphertext[1]);
for(int i=0;i<arr.length;i++)
ciphertext[i] = modular_exponentiation(ciphertext[i], e, n);
return ciphertext;
}
//Decryption method
//Input: ciphertext, d and n, where:
//Ciphertext is an array of longs, each element represents the ciphertext of the ith block
//d is the private key
//n is the modulus
//Output: Plaintext as a String
public String decrypt(long[] ciphertext, long d, long n)
{
String plaintext="";
for(int i=0;i<ciphertext.length;i++)
plaintext+=int_to_String(modular_exponentiation(ciphertext[i],d,n));
return plaintext;
}
public static void main(String[] args)
{
R cipher= new R(); //Create an instance of your cryptographic system
//Before starting, you must generate your keys
long[] n_e_d= cipher.generate_keys();
System.out.println("Modulus n is: "+n_e_d[0]);
System.out.println("Public key e is: "+n_e_d[1]);
System.out.println("Private key d is: "+ n_e_d[2]);
//Encrypt the plaintext using exponent e and modulus n
long[] ciphertext=cipher.encrypt("IMAHACKER", n_e_d[1],n_e_d[0]);
//Print each of the ciphertext blocks
for (long block: ciphertext)
System.out.print (block+ " ");
System.out.println();
//Decrypt the ciphertext and print out the plaintext
String plaintext=cipher.decrypt(ciphertext, n_e_d[2], n_e_d[0]);
System.out.println("Decrypting ciphertext we get: "+plaintext);
}
}
Related
I'm an Engineering Student and I'm stuck on this part of the Affine Cypher.
import java.util.Scanner;
public class abcd {
public static int a, b;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter key(a,b): ");
a = sc.nextInt();
b = sc.nextInt();
Scanner hj = new Scanner(System.in);
System.out.print("Enter String: ");
String word = hj.nextLine();
sc.close();
hj.close();
System.out.println("Cyphered text: " + cypher(word));
System.out.println("Decyphered text: " + decypher(cypher(word)));
}
public static String cypher(String plaintext) {
String CT = "";
for (int i = 0; i < plaintext.length(); i++) {
char x = plaintext.charAt(i);
int val = (char)x-97;
int C = ((a* val + b)%26);
char n = (char) (C + 97);
CT = CT + n;
}
return CT;
}
public static int inv (int a, int b) {
a=a%b;
for (int x = 1; x<26; x++) {
if ((a*x)%26==1) {
return x;
}
}
return 1;
}
public static String decypher(String cyphertext) {
String t = "";
for (int i = 0; i<cyphertext.length(); i++) {
char x = cyphertext.charAt(i);
int val = (char)x - 97;
int D = ((inv(a, 26)*(val-b))%26);
char n = (char)(D + 97);
t = t + n;
}return t;
}
}
The cyphered text shows the desired output but the deciphered text doesn't match the original text.
Here is my console input and output:
Enter key(a,b):
7
2
Enter String: hello
Cyphered text: zebbw
Decyphered text: heRRo
I was expecting the deciphered text to match the original text since that is what it was supposed to do.
As Joachim Sauer and Tan Yu Hau Sean suggest, % does things you may not expect on negative numbers. If a is negative, a%b will be a number between -b and 0.
If you add a method like this
public static int mod(int a, int b) {
return (a%b+b)%b;
}
and replace your instances of % with calls to it, e.g.:
int C = mod(a* val + b,26);
things will work a lot better.
How to fix this issue?
java.lang.NumberFormatException: at java.lang.NumberFormatException.forInputString(Unknown Source)
I am doing some example problem and my code is working fine for the first string and digit. (Commented one)
But when change the new string and digit (Current one) I am getting this error :
java.lang.NumberFormatException: For input string: "299858953917872714814599237991174513476623756395992135212546127959342974628712329595771672911914471"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at com.codejam.q1.problems.maxResult.removeDigit(maxResult.java:21)
at com.codejam.q1.problems.maxResult.main(maxResult.java:10)
Here is my code. Anywhere I am missing something ?
public class maxResult {
public static void main(String[] args) {
//String str = "1231";
String str = "2998589353917872714814599237991174513476623756395992135212546127959342974628712329595771672911914471";
//char digit = '1';
char digit = '3';
System.out.println(removeDigit(str,digit));
}
public static String removeDigit(String number, char digit) {
long result = 0;
for(int i = 0; i<number.length(); i++) {
char num = number.charAt(i);
if(num == digit) {
String myStr = number.substring(0, i) + number.substring(i + 1);
try{
long myNum = Long.parseLong(myStr);
if(myNum > result) {
result = myNum;
}
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
}
}
String s = String.valueOf(result);
return s;
}
}
Even though I change int to long but no change in result.
Your number is too big for a long value. The maximum long value is 9,223,372,036,854,775,807. You can use BigInteger, which essentially has no limit.
Using long
long result = 0;
// ...
long myNum = Long.parseLong(myStr);
if(myNum > result) {
result = myNum;
}
// ...
String s = String.valueOf(result);
return s;
Using BigInteger
import java.math.BigInteger;
// ...
BigInteger result = BigInteger.ZERO;
// ...
BigInteger myNum = new BigInteger(myStr);
result = myNum.max(result);
// ...
return result.toString();
The number is too long for a long. Longs go from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,808.
Try doing this :
public static String removeDigit(String number, char digit) {
double temp = 0;
String result="";
for(int i = 0; i<number.length(); i++) {
char num = number.charAt(i);
if(num == digit) {
String myStr = number.substring(0, i) + number.substring(i + 1);
try{
double myNum = Double.parseDouble(myStr);
if(myNum > temp) {
temp = myNum;
result=myStr;
}
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
}
}
return result;
}
The problem you get is that you are exceeding the limit of the int and the long. Let us see the limits of some number storing types and then use the best one:
Type
Size
Value
Exceeds
int
32 bit
-2,147,483,648 to 2,147,483,647
Yes
long
64 bit
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Yes
float
32 bit
3.40282347 x 1038 to 1.40239846 x 10-45
Yes
double
64 bit
1.7976931348623157 x 10308 to 4.9406564584124654 x 10-324
Yes
BigInteger
32 bit
2^64billion
No
Here, we find that BigInteger is the class we need to use. So, instead of using a long or int for it, use BigInteger. To know more about BigInteger, visit here.
Also to know how to use a big integers refer to the answer here
You can use BigDecimal instead of long.
public class Application {
public static void main(String[] args) {
//String str = "1231";
String str = "2998589353917872714814599237991174513476623756395992135212546127959342974628712329595771672911914471";
//char digit = '1';
char digit = '3';
System.out.println(removeDigit(str,digit));
}
public static BigDecimal removeDigit(String number, char digit) {
BigDecimal result = BigDecimal.ZERO;
for(int i = 0; i<number.length(); i++) {
char num = number.charAt(i);
if(num == digit) {
String myStr = number.substring(0, i) + number.substring(i + 1);
try{
BigDecimal myNum = new BigDecimal(myStr);
if(myNum.compareTo(result)>0) {
result = myNum;
}
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
}
}
return result;
}
}
I have a simple java code that encrypts and decrypts numbers using the RSA algorithm
If anyone could help me to make this code reads a text (string) from the user and decrypt it instead of only numbers but in a simple way so I can draw a flowchart for the code afterward :)
https://codedost.com/css/java-program-rsa-algorithm/
import java.util.*;
import java.math.*;
public class RSA {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int p, q, n, z, d = 0, e, i;
System.out.println("Enter the number to be encrypted and decrypted");
int msg = sc.nextInt();
double c;
BigInteger msgback;
System.out.println("Enter 1st prime number p");
p = sc.nextInt();
System.out.println("Enter 2nd prime number q");
q = sc.nextInt();
n = p * q;
z = (p - 1) * (q - 1);
System.out.println("the value of z = " + z);
for (e = 2; e < z; e++) {
if (gcd(e, z) == 1) // e is for public key exponent
{
break;
}
}
//e should be in the range 1-z
System.out.println("the value of e = " + e);
// calculate d
for (i = 0; i <= 9; i++) {
int x = 1 + (i * z);
if (x % e == 0) //d is for private key exponent
{
d = x / e;
break;
}
}
System.out.println("the value of d = " + d);
c = (Math.pow(msg, e)) % n;
//Encryptin C = msg ^e mod n
System.out.println("Encrypted message is : -");
System.out.println(c);
//converting int value of n to BigInteger
BigInteger N = BigInteger.valueOf(n);
//converting float value of c to BigInteger
BigInteger C = BigDecimal.valueOf(c).toBigInteger();
msgback = (C.pow(d)).mod(N);
//Decrypt , P = Cˆd mod N , msgback = P
System.out.println("Derypted message is : -");
System.out.println(msgback);
}
static int gcd(int e, int z) {
if (e == 0) {
return z;
} else {
return gcd(z % e, e);
}
}
}
As you already implemented encryption and decryption for single number you can easily extend it and provide support for longer messages. In fact, the only change you need is to perform same operation N times (for each character in input message). Have a look at below code:
import java.util.*;
import java.math.*;
public class Rsa {
private static final Scanner sc = new Scanner(System.in);
private int p, q, n, z, d = 0, e, i;
public Rsa() {
System.out.println("Enter 1st prime number p");
p = sc.nextInt();
System.out.println("Enter 2nd prime number q");
q = sc.nextInt();
n = p * q;
z = (p - 1) * (q - 1);
System.out.println("the value of z = " + z);
for (e = 2; e < z; e++) {
if (gcd(e, z) == 1) // e is for public key exponent
{
break;
}
}
//e should be in the range 1-z
System.out.println("the value of e = " + e);
// calculate d
for (i = 0; i <= 9; i++) {
int x = 1 + (i * z);
if (x % e == 0) //d is for private key exponent
{
d = x / e;
break;
}
}
System.out.println("the value of d = " + d);
}
private static int gcd(int e, int z) {
if (e == 0) {
return z;
} else {
return gcd(z % e, e);
}
}
double encrypt(int msg) {
//Encrypting C = msg ^e mod n
return (Math.pow(msg, e)) % n;
}
double[] encrypt(String msg) {
int[] charactersAsNumbers = new int[msg.length()];
for(int i = 0; i < msg.length(); i++) {
charactersAsNumbers[i] = msg.codePointAt(i);
}
System.out.println("Plain text as sequence of numbers: " + Arrays.toString(charactersAsNumbers));
double[] encryptedMsg = new double[msg.length()];
for(int i = 0; i < charactersAsNumbers.length; i++) {
encryptedMsg[i] = encrypt(charactersAsNumbers[i]);
}
return encryptedMsg;
}
BigInteger decrypt(double encrypted) {
//converting int value of n to BigInteger
BigInteger N = BigInteger.valueOf(n);
//converting float value of c to BigInteger
BigInteger C = BigDecimal.valueOf(encrypted).toBigInteger();
//Decrypt , P = Cˆd mod N , msgback = P
return (C.pow(d)).mod(N);
}
String decrypt(double[] encrypted) {
StringBuilder builder = new StringBuilder();
for(double encryptedCharacter: encrypted) {
BigInteger decryptedCharacter = decrypt(encryptedCharacter);
builder.append(Character.toChars(decryptedCharacter.intValue()));
}
return builder.toString();
}
public static void main(String args[]) {
System.out.println("Enter the text to be encrypted and decrypted");
String msg = sc.nextLine();
Rsa rsa = new Rsa();
double[] c = rsa.encrypt(msg);
System.out.println("Encrypted message is: " + Arrays.toString(c));
String msgBack = rsa.decrypt(c);
System.out.println("Decrypted message is: " + msgBack);
}
}
What I did here is:
Overloaded encrypt and decrypt methods. Now they support longer messages; encrypt accepts String parameter and returns double[], decrypt accepts double[] and returns String
Logic moved to methods without changing original data types and general flow
I know given solution is not optimal but I guess performance and code style aren't critical for you in this case.
Hope it helps you solve your problem.
Edit: I improved logs slightly, here is the sample output (and input):
Enter the text to be encrypted and decrypted
Secret.
Enter 1st prime number p
13
Enter 2nd prime number q
19
the value of z = 216
the value of e = 5
the value of d = 173
Plain text as sequence of numbers: [83, 101, 99, 114, 101, 116, 46]
Encrypted message is: [239.0, 43.0, 112.0, 95.0, 43.0, 51.0, 50.0]
Decrypted message is: Secret.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I need to design an algorithm where each number is encoded to an alphabet, for example:
1=A, 2=B, 3=C...26=Z
Given a set of numbers, I have to translate them to a combination of strings. For example:
123 can be translated to - ABC(123), AW(1 23) and LC(12 3)
Write an algorithm to find the combinations for number - 123123123.
Now here is what I wrote and I find it inefficient because of multiple "for" loops. Is there any better way I can rewrite this algorithm?
public class ValidCombinations {
Map<Integer, String> mapping = new HashMap<Integer, String>();
public void run() {
String s = "123123123";
/*Convert String to int[]*/
char[] cArray = s.toCharArray();
int[] input = new int[cArray.length];
for (int i=0; i<cArray.length; i++) {
input[i] = Character.getNumericValue(cArray[i]);
}
Set<String> output = new HashSet<String>();
for (int i='A'; i<='Z'; i++) {
mapping.put(i - 'A' + 1, String.valueOf((char)i));
}
for (int i=0; i<input.length; i++) {
if (mapping.containsKey(input[i])) {
output.add(precombine(i, input) + mapping.get(input[i]) + postcombine(i, input));
if (i+1<input.length) {
if (mapping.containsKey(input[i]*10 + input[i+1])) {
output.add(precombine(i, input) + mapping.get(input[i]*10 + input[i+1]) + postcombine(i+1, input));
}
}
}
}
System.out.println(output);
}
public String precombine(int i, int[] input) {
String residue="";
for (int m=0; m<i; m++) {
residue += mapping.get(input[m]);
}
return residue;
}
public String postcombine(int i, int[] input) {
String residue="";
for (int k=i+1; k<input.length; k++) {
residue += mapping.get(input[k]);
}
return residue;
}
public static void main(String[] args) {
ValidCombinations v = new ValidCombinations();
v.run();
}
}
For '123' - [ABC, AW, LC]
For '123123123' - [LCABCABC, AWABCABC, ABCAWABC, ABCLCABC, ABCABCLC, ABCABCABC, ABCABCAW]
This problem is crying out for recursion. Here's a quick and dirty implementation that takes the input "number" in as a string and uses substring() to consume the digits. You could adapt it to use numerical methods to get the first (or first two) decimal digits from an integer if you prefer.
If you choose to work directly from an int, it would probably be easier to start at the end (working with the least-significant-digits) than at the beginning -- lastDigit = number % 10; otherDigits = number / 10
public List<String> encodings(String number) {
List<String> out = new ArrayList<>();
addEncodings("", number, out);
return out;
}
private void addEncodings(String prefix, String number, List<String> out) {
if (number.length() == 0) {
out.add(prefix);
} else {
addParsingNDigits(1, prefix, number, out);
addParsingNDigits(2, prefix, number, out);
}
}
private void addParsingNDigits(int digits, String prefix, String number, List<String> out) {
if (number.length() >= digits) {
char encodedChar = parseChars(number, digits);
if (encodedChar >= 'A' && encodedChar <= 'Z') {
addEncodings(prefix + encodedChar, number.substring(digits), out);
}
}
}
private char parseChars(String number, int length) {
int intVal = Integer.parseInt(number.substring(0, length));
return (char) ('A' + intVal - 1);
}
I don't think your solution will find all possible encodings -- I think you need some sort of stack to solve it. The solution above implicitly uses the execution stack, because of recursive method calls. Another solution could explicitly place objects representing "todo" calculations onto a stack data structure in the heap:
private static class StackItem {
public StackItem(String prefix, String number) {
this.prefix = prefix;
this.number = number;
}
public String prefix;
public String number;
}
public List<String> encodings(String number) {
List<String> results = new ArrayList<>();
Stack<StackItem> stack = new Stack<>();
stack.push(new StackItem("", number));
while (!stack.isEmpty()) {
StackItem current = stack.pop();
if (current.number.equals("")) {
results.add(current.prefix);
} else {
addToStackTakingNChars(2, current, stack);
addToStackTakingNChars(1, current, stack);
}
}
return results;
}
private void addToStackTakingNChars(int n, StackItem current, Stack<StackItem> stack) {
if (current.number.length() >= n) {
char c = parseChars(current.number, n);
if (c >= 'A' && c <= 'Z') {
stack.push(new StackItem(current.prefix + c, current.number.substring(n)));
}
}
}
Although "println debugging" is generally a bad habit, it would probably be a good learning exercise to run these examples with some println()s to observe how it works.
I think you could split the String in the middle (recursively), search for all combinations in both substrings and build the cross product. To not miss any combinations we have to also build the cross product for the two substrings you get by splitting in the middle with an offset of one. Something like this:
private static int[] values;
public static final Set<String> solve(String s) {
values = new int[s.length()];
for (int i = 0; i < values.length; i++)
values[i] = s.charAt(i) - '0';
return solve(0, values.length);
}
private static final Set<String> solve(int start, int len) {
Set<String> ret = new HashSet<>();
if (len == 1) {
ret.add("" + ((char)(values[start] - 1 + 'A')));
} else if (len == 2) {
ret.add("" + ((char)(values[start] - 1 + 'A')) +
((char)(values[start + 1] - 1 + 'A')));
int n = values[start] * 10 + values[start + 1];
if (n <= 26)
ret.add("" + ((char)(n - 1 + 'A')));
} else {
int next = start + len / 2;
cross(solve(start, next - start), solve(next, start + len - next), ret);
cross(solve(start, next - start + 1), solve(next + 1, start + len - next - 1), ret);
}
return ret;
}
private static final void cross(Set<String> a, Set<String> b, Set<String> target) {
for (Iterator<String> itr = a.iterator(); itr.hasNext();) {
String s = itr.next();
for (Iterator<String> itr2 = b.iterator(); itr2.hasNext();) {
target.add(s + itr2.next());
}
}
}
Btw. the solution for "123123123" are the following 27 strings: LCABCAW, LCABCLC, ABCLCABC, ABCLCAW, ABCAWLC, AWLCABC, ABCAWAW, ABCAWABC, ABCLCLC, ABCABCABC, LCAWLC, LCAWAW, AWABCLC, LCAWABC, AWABCAW, LCLCAW, AWABCABC, LCLCLC, LCLCABC, LCABCABC, AWAWLC, AWAWABC, AWAWAW, ABCABCLC, ABCABCAW, AWLCAW, AWLCLC.
Why not just use the ascii value?
All you would need to do would be to convert the number to a String Integer.toString(num) and then run a for-loop through the .length() of the String and pull the .charAt(i) from the String convert that back to an int and then add 16 to it. Then you would just need to cast to a char. like so:
int a = 123;
String str = Integer.toString(a);
char[] chars = new char[str.length()];
for(int i=0,n=str.length();i<n;i++){
chars[i] = (char)(str.charAt(i)+16);
}
String message = String.valueOf(chars);
This problem can be done in o(fib(n+2)) time with a standard DP algorithm.
We have exactly n sub problems and button up we can solve each problem in o(fib(i)) time.
Summing the series gives fib (n+2).
If you consider the question carefullly you see that it is a fibunacci series.
I took a standart code and just changed it a bit to fit our conditions.
The space is obviously bound to the size of all solutions o(fib(n)).
Consider this code:
Map<Integer, String> mapping = new HashMap<Integer, String>();
List<String > iterative_fib_sequence(int input) {
int length = Math.floor(Math.log10(Math.abs(input))) + 1;
if (length <= 1)
{
if (length==0)
{
return "";
}
else//input is a-j
{
return mapping.get(input);
}
}
List<String> b = new List<String>();
List<String> a = new List<String>(mapping.get(input.substring(0,0));
List<String> c = new List<String>();
for (int i = 1; i < length; ++i)
{
int dig2Prefix = input.substring(i-1, i); //Get a letter with 2 digit (k-z)
if (mapping.contains(dig2Prefix))
{
String word2Prefix = mapping.get(dig2Prefix);
foreach (String s in b)
{
c.Add(s.append(word2Prefix));
}
}
int dig1Prefix = input.substring(i, i); //Get a letter with 1 digit (a-j)
String word1Prefix = mapping.get(dig1Prefix);
foreach (String s in a)
{
c.Add(s.append(word1Prefix));
}
b = a;
a = c;
c = new List<String>();
}
return a;
}
I have this input like
String s = "6" , ss="99 , sss = "99999";
i need to store these values in an int reference variable ,
without using Integer.parseInt
any suggestion ? , no full code , just the hints ??
What about Scanner?
int a=new Scanner(s).nextInt();
Without util.
public static int parseInt(String s)
{
int ans=0;
for(int i=s.length()-1;i>=0;i--)
{
ans+=(s.charAt(i)-'0');
ans*=10;
}
return ans/10;
}
public class MyStringToNumber {
public static int convert_String_To_Number(String numStr){
char ch[] = numStr.toCharArray();
int sum = 0;
//get ascii value for zero
int zeroAscii = (int)'0';
for(char c:ch){
int tmpAscii = (int)c;
sum = (sum*10)+(tmpAscii-zeroAscii);
}
return sum;
}
public static void main(String a[]){
System.out.println("\"3256\" == "+convert_String_To_Number("3256"));
System.out.println("\"76289\" == "+convert_String_To_Number("76289"));
System.out.println("\"90087\" == "+convert_String_To_Number("90087"));
}
}
See more at this URL.
Try to get each char from the string and then the value of each char. 0 has a value of 48 so
char c = '9';
int i = c - 48;
Now i = 9. After that you only need to multiply this value with the appropriate power of 10 and add it to the total
public class ConvertIntoInt {
public static void main(String []args) {
String numStr = "3256";
char ch[] = numStr.toCharArray();
int sum = 0;
// Get ASCII value for zero
int zeroAscii = (int)'0';
for (char c:ch) {
int tmpAscii = (int)c;
System.out.println("Temp Ascii:" + tmpAscii);
sum = (sum * 10) + (tmpAscii - zeroAscii);
System.out.println(sum);
}
System.out.println(sum);
}
}