How to print out the digits of an integer of any length? - variables

This program is works as long as the divide variable is of the same base 10 power as the variable num, in this case the number is 12345 so divide needs to be 10000. While this works for 5 digit numbers, anything with more or less than 5 digits will not have their individual digits printed out. How do I configure divide to have be of the same base 10 power as num automatically?
public class lab5testing
{
public static void main (String args[])
{
int num = 12345, digit = 0, divide = 10000;
if (num != 0)
{
while(num != 0 )
{
digit = ((num/divide)%10);
System.out.println(digit);
divide /= 10;
if (divide == 0)
{
num = 0;
}
}
}
else
{
System.out.println(num);
}
}
}

Maybe you should try with this :
int length = (int)(Math.log10(num)+1);
and then :
int divide = Math.pow(10,lengh);

Related

Why doesn't this While loop work as intended?

Hey guys, newbie here. One question, can't understand why this while loop doesn't work even when I entered a int bigger than 9 to the variable num, the while loop should repeat itself until the expression is false, and it doesn't, no output even. Am I missing something here? Thanks in advance.
fun main () {
while(true) {
println ("\nWrite a positive number: ")
var num = readLine()!!.toInt()
var sum = 0
if (num > 9) {
while (num > 9) {
var digit = num % 10
sum = sum + digit
num = num / 10
}
println("\nDigit Sum: $sum")
} else if (num in 1..9) {
println("\nDigit Sum for the number $num is $num")
} else {
println("\nInvalid input, try again.")
}
}
}
The issue is that you are not summing the last num when it gets less or equal to 9. You can even simplify your code a bit. Try the following:
fun main() {
while(true) {
println ("\nWrite a positive number: ")
val insertedNumber = readLine()!!.toInt()
var num = insertedNumber
var sum = 0
while (num > 9) {
val digit = num % 10
sum = sum + digit
num = num / 10
}
sum = sum + num
println("\nDigit Sum for the number $insertedNumber is $sum")
}
}
You don't need to redeclare the variables every time
var sum = sum + digit
var num = num / 10
So simply remove var
sum = sum + digit
num = num / 10

Roman Numerals. Could you point out my mistakes further down the road?

Beginner here. This piece of code converts number into roman numerals in multiples of 50 if not 10 if not 9 and down to 0. Methods are so intertwined. Is there something (just at a glance) you could suggest I should avoid doing? Thank You.
public static void main(String[] args) {
System.out.println(fiftyAndAbove(37));
}
public static String nineAndDown(int number) {
String one = "I", five = "V", ten = "X", sum = "";
if(number == 5) {
return five;
} else if(number == 9) {
return one + ten;
}
else if(number > 5) {
for(int i=1; i<=number-5; i++) {
sum += one;
}
return five + sum;
} else {
if(number == 4 ) {
return one + five;
} else
for(int i=1; i <=number; i++) {
sum += one;
}
} return sum;
}
public static String tenAndAbove(int number) {
int remainder = number % 10, numberOftens = number/10;
String ten = "X", sum = "";
if(numberOftens > 0) {
while(numberOftens > 0) {
sum += ten;
numberOftens -= 1;
}
}
return sum + nineAndDown(remainder);
}
public static String fiftyAndAbove(int number) {
int remainder = number % 50, numberOfFifty = number/50;
String fifty = "L", sum = "";
if(numberOfFifty > 0) {
while(numberOfFifty > 0) {
sum += fifty;
numberOfFifty -= 1;
}
}
return sum + tenAndAbove(remainder);
}
Is there something (just at a glance) you could suggest I should avoid doing?
I'd not unnecessarily complicate the logic as with
if(numberOfFifty > 0) {
while(numberOfFifty > 0) {
…
}
}
which is equivalent to
while (numberOfFifty > 0)
{
…
}
You could also have a look at this implementation and see what you prefer:
import java.util.Arrays;
…
public static String fiftyAndAbove(int number)
{
int remainder = number%50, numberOfFifty = number/50;
char [] Ls = new char [numberOfFifty];
Arrays.fill(Ls, 'L');
return new String(Ls) + tenAndAbove(remainder);
}
You have four places like this in your program where you need a string of a character repeated. If you're willing to require a certain Java version or above, you can also use one of the methods described at Java: String - add character n-times; otherwise I'd suggest to use a function to do it.
You could also think about whether you find
String one = "I", five = "V", ten = "X", sum = "";
if(number == 5) {
return five;
} else if(number == 9) {
return one + ten;
}
really better than
if (number == 5) return "V";
if (number == 9) return "IX";

Shorten the process of finding the sum of positive number (users input 6 different intteger)

I nedd to find the fatest and shortest way to calculate the sum of positive integer that the user input in.
else if(num1<0 && num2 >0 && num3>0 && num4>0 && num5>0 &&num6>0){
totalPositiveNumber =num2 + num3 + num4 + num5 + num6;
System.out.println("The sum of positive integer is: " + totalPositiveNumber);
}
You can read the numbers and store them in an array. Later iterate over the array and sum only, when number is greater than 0. Check below for sample code for reading input from System.in using Scanner class.
import java.util.Scanner;
public class Sum {
public static void main(String args[]) {
Scanner read = new Scanner(System.in);
int array[] = new int[6];
int sum = 0;
for (int i = 0; i<6; i++) {
array[i] = read.nextInt();
}
for (int i = 0; i<6; i++) {
if (array[i] > 0) {
sum = sum + array[i];
}
}
System.out.println(sum);
}
}

Numbers into words issue C

I am trying to write a program that will take an integer input, and then convert it to words. for example: 123, one two three. Also -3908, negative three nine zero eight.
My code works 90% of the time, the only issue coming along when i am putting one or more zeros on the end of the integer. eg. 70800 will come up as seven zero eight. It completely misses the end zeros. I understand why that is happening but does anybody know if there is a way around it.
PS(i am not allowed as a part of this task to accept the input as a string and split it into an array, so it would be best if the answer is based off this code).
int main(int argc, const char * argv[])
{
#autoreleasepool {
float abNumber;
int i = 0;
float number;
float result;
float firstNumber;
printf("type a number: ");
scanf("%f", &firstNumber);
abNumber = abs(firstNumber);
if (firstNumber < 0) {
printf("negative ");
}
number = abNumber;
while (number >= 10) {
number = number / 10;
i++;
}
do {
float countNumber = abNumber;
float power = powf(10, -i);
float powerNo2 = powf(10, i);
countNumber = countNumber * power;
result = floorf(countNumber);
if (result == 9){
printf("nine ");
}
if (result == 8){
printf("eight ");
}
if (result == 7){
printf("seven ");
}
if (result == 6){
printf("six ");
}
if (result == 5){
printf("five ");
}
if (result == 4){
printf("four ");
}
if (result == 3){
printf("three ");
}
if (result == 2){
printf("two ");
}
if (result == 1){
printf("one ");
}
if (result == 0){
printf("zero ");
}
while (abNumber > powerNo2) {
abNumber = abNumber - powerNo2;
}
i--;
} while (i >= 0);
}
return 0;
}
The main error seems to be that
while (abNumber > powerNo2) {
should be
while (abNumber >= powerNo2) {
But I would recommend not to use floating point arithmetic at all, to avoid
possible rounding errors. The same can be achieved with simple integer arithmetic
(I have omitted the "negative case" for simplicity):
int number;
printf("type a number: ");
scanf("%d", &number);
// Determine highest power of 10 that is <= the given number:
int power = 1;
while (10 * power <= number) {
power *= 10;
}
// Extract each digit:
while (power > 0) {
int digit = (number / power) % 10;
/*
* Use switch/case to print 'digit' as a string ...
*/
power /= 10;
}
I would go for recursive solution, like that
int print(int num)
{
if( num )
{
int mod = num%10;
print(num/10);
switch(mod)
{
case 0:printf(" zero");break;
case 1:printf(" one");break;
case 2:printf(" two");break;
case 3:printf(" three");break;
}
}
return 0;
}
Recursivy divide the number untill nothing left of it, on the way back print the mod.
Why don't you just input the number as a string then loop through each character:
Exemple: http://ideone.com/E8QspN
Input:
-12003200
Output:
negative one two zero zero tree two zero zero
Code:
#include <stdio.h>
int main(int argc, char *argv[])
{
char input[25];
scanf("%s", input);
int i = 0;
while (input[i] != '\0') {
switch(input[i]) {
case '-' :
printf("negative");
break;
case '0' :
printf("zero");
break;
case '1' :
printf("one");
break;
case '2' :
printf("two");
break;
case '3' :
printf("tree");
break;
case '4' :
printf("four");
break;
case '5' :
printf("five");
break;
case '6' :
printf("six");
break;
case '7' :
printf("seven");
break;
case '8' :
printf("eight");
break;
case '9' :
printf("nine");
break;
default :
break;
}
printf(" ");
i++;
}
return 0;
}
Consider the following:
Code
#include <stdio.h>
#include <stdlib.h>
const char *numbers[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
void printNum(int num);
int main(void)
{
int num;
printf("Enter a number: ");
scanf("%u", &num);
printNum(num);
printf("\n");
return 0;
}
void printNum(int num)
{
int absNum = abs(num);
if(absNum > 9)
printNum(num / 10);
if((absNum < 10) && (num < 0))
printf("negative");
printf(" %s", numbers[absNum % 10]);
}
Example Output
Enter a number: 2582
two five eight two
Enter a number: -943
negative nine four three
Enter a number: 1000
one zero zero zero
Enter a number: -1000
negative one zero zero zero
Logic
Get an integer from user.
Send to recursive function.
Keep recursing until the least significant digit is left. This is to print in the correct order.
Print digit as a string by using a lookup table.
Keep someone a high five.
To Do
Error checking

How to increase an ipv6 address based on mask in java?

i am trying to increment ipv6 address based on mask.
i am getting problem when there is F in place of increment.
could any one plz check this
public String IncrementIPV6ForPrefixLength (String IPv6String, int times) throws UnknownHostException
{
int result , carry = 0, i;
int bits;
int mask=0;
int index=IPv6String.indexOf("/");
mask=Integer.parseInt(IPv6String.substring(index+1, IPv6String.length()));
IPv6String=IPv6String.substring(0, index);
InetAddress iaddr=InetAddress.getByName(IPv6String);
byte[] IPv6Arr=iaddr.getAddress();
if(mask > 128 || mask < 0)
return null;
i = mask/8;
bits = mask%8;
if(bits>0)
{
result = ((int)(IPv6Arr[i]>>(8-bits))) + times;
IPv6Arr[i] =(byte) ((result << (8-bits)) | (IPv6Arr[i] & (0xff >> (bits))));
carry = (result << (8-bits))/256;
times /= 256;
}
i--;
for(;i>=0;i--)
{
result = ((int)IPv6Arr[i]) + ((times + carry)& 0xFF);
IPv6Arr[i] = (byte)(result % 256);
carry = result / 256;
if(carry == 0)
{
iaddr=InetAddress.getByAddress(IPv6Arr);
String s=iaddr.toString();
if(s.indexOf('/') != -1){
s = s.substring(1, s.length()).toUpperCase();
}
StringBuffer buff =new StringBuffer("");
String[] ss = s.split(":");
for(int k=0;k<ss.length;k++){
int Differ = 4 - ss[k].length();
for(int j = 0; j<Differ;j++){
buff.append("0");
}
buff.append(ss[k]);
if(k!=7)buff=buff.append(":");
}
return buff.toString()+"/"+mask;
}
times /= 256;
}
return null;
}
input like this:
FD34:4FB7:FFFF:A13F:1325:2252:1525:325F/48
FD34:41B7:FFFF::/48
FD34:4FBF:F400:A13E:1325:2252:1525:3256/35
output like this
if increment by 1
FD34:4FB8:0000:A13F:1325:2252:1525:325F/48
FD34:41B8:0000::/48
FD34:4FC0:0400:A13E:1325:2252:1525:3256/35
if increment by 2
FD34:4FB8:0001:A13F:1325:2252:1525:325F/48
FD34:41B8:0001::/48
FD34:4FC0:1400:A13E:1325:2252:1525:3256/35
can u plz find where i am doing wrong.
Disregarding the posted code, try to model the operation as a direct numerical operation on the 128-bit number that the IPv6 address really is. Convert to BigInteger and use BigInteger.add.