تبدیل از هر مبنایی به مبنای 10 :
// Java program to convert
// a number from any base
// to decimal
import java.io.*;
class GFG
{
// To return value of a char.
// For example, 2 is returned
// for '2'. 10 is returned
// for 'A', 11 for 'B'
static int val(char c)
{
if (c >= '0' && c <= '9')
return (int)c - '0';
else
return (int)c - 'A' + 10;
}
// Function to convert a
// number from given base
// 'b' to decimal
static int toDeci(String str,
int base)
{
int len = str.length();
int power = 1; // Initialize
// power of base
int num = 0; // Initialize result
int i;
// Decimal equivalent is
// str[len-1]*1 + str[len-1] *
// base + str[len-1]*(base^2) + ...
for (i = len - 1; i >= 0; i--)
{
// A digit in input number
// must be less than
// number's base
if (val(str.charAt(i)) >= base)
{
System.out.println("Invalid Number");
return -1;
}
num += val(str.charAt(i)) * power;
power = power * base;
}
return num;
}
// Driver code
public static void main (String[] args)
{
String str = "11A";
int base = 16;
System.out.println("Decimal equivalent of "+
str + " in base "+ base +
" is "+ " "+
toDeci(str, base));
}
}
// This code is contributed
// by anuj_67.
تبدیل از 10 به هر مبنایی :
// Java Program to convert decimal to any given base
import java.lang.*;
import java.io.*;
import java.util.*;
class GFG
{
// To return char for a value. For
// example '2' is returned for 2.
// 'A' is returned for 10. 'B' for 11
static char reVal(int num)
{
if (num >= 0 && num <= 9)
return (char)(num + 48);
else
return (char)(num - 10 + 65);
}
// Function to convert a given decimal number
// to a base 'base' and
static String fromDeci(int base1, int inputNum)
{
String s = "";
// Convert input number is given
// base by repeatedly dividing it
// by base and taking remainder
while (inputNum > 0)
{
s += reVal(inputNum % base1);
inputNum /= base1;
}
StringBuilder ix = new StringBuilder();
// append a string into StringBuilder input1
ix.append(s);
// Reverse the result
return new String(ix.reverse());
}
// Driver code
public static void main (String[] args)
{
int inputNum = 282, base1 = 16;
System.out.println("Equivalent of " + inputNum +
" in base "+base1+" is " +
fromDeci(base1, inputNum));
}
}
// This code is contributed by mits
بررسی پالیندورم بودن عدد :
// Java implementation of the approach
public class GFG {
// Function that returns true if
// str is a palindrome
static boolean isPalindrome(String str)
{
// Pointers pointing to the beginning
// and the end of the string
int i = 0, j = str.length() - 1;
// While there are characters toc compare
while (i < j) {
// If there is a mismatch
if (str.charAt(i) != str.charAt(j))
return false;
// Increment first pointer and
// decrement the other
i++;
j--;
}
// Given string is a palindrome
return true;
}
// Driver code
public static void main(String[] args)
{
String str = "geeks";
if (isPalindrome(str))
System.out.print("Yes");
else
System.out.print("No");
}
}