Write a program to find the length of the integer number.
Example:
Input: 123
Output: 3
Approach 1:
Java
public class IntegerNumberLength {public static void main(String[] args) {int num = 123;int lenght = length(num);System.out.println("Length is " + lenght);}// find length of given integerprivate static int length(int num) {int length = 0;// Iterate till the number become 0while (num > 0) {// increate the lengthlength++;// num=num/10num /= 10;}return length;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the legth//of given numberint lengthNumber(int num){int length=0;//iterate tiil the//number becomes 0while(num>0){//increment the lengthlength++;//num=num/10num=num/10;}return length;}int main(){int num=123;int lenght=lengthNumber(num);cout<<"Length of number is ";cout<<lenght<<"\n";return 0;}
Approach 2: Using log10() function.
Java
public class IntegerNumberLength1 {public static void main(String[] args) {int num = 123;int lenght = length(num);System.out.println("Length is " + lenght);}// find length of given integerprivate static int length(int num) {// base case, log10(0) is undefinedif (num == 0)return 0;int length = (int) (Math.log10(num) + 1);return length;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the legth//of given numberint lengthNumber(int num){// base case, log10(0) is undefinedif (num == 0)return 0;//length of number is log10(n)int length=log10(num)+1;//return the length of numberreturn length;}int main(){int num=123;int lenght=lengthNumber(num);cout<<"Length of number is ";cout<<lenght<<"\n";return 0;}
No comments:
Post a Comment